如何将值从一个Select更改为另一个Select

How to change value from one Select to another?

本文关键字:Select 一个 另一个      更新时间:2023-09-26

我有两个Selects,在html代码中有几个选项:

<select name="t" id="t">
<option value="0">Overall</option>
<option value="1">t_name</option></select>
<select name="m" id="m">
<option value="0">back to Overall</option>
<option value="1">m_some</option></select>

我的问题是,只有在用户在第二个名为"m"的Select中选择值"0"(返回到"总体"(的情况下,如何强制将值从第一个名为"t"的Select更改为"0"(总体(?最后提交表格。

--编辑--

现在,由于建议,我尝试以这种方式做到这一点:

<script>
$(function(){
  $('#m, #t').change(function(){
    if($('#m').val() == '0')
      $('#t').val('0').change();
      $('form#myform').submit();   
  });
});
</script>

每当我更改Select"m"或"t"时,此脚本都会提交表单,但当我将Select"m(更改为值"0"时除外(脚本仅以正确的方式将"t"更改为"0"而不提交(。为什么?

<html>
<body>
    <form name="form1" id="form1">
    <select id="t" name="t" onchange="this.form.submit();">
        <option value="0">Overall</option>
        <option value="1">t_name</option>
    </select>
    <select name="m" onchange="setposition(this.value)">
        <option value="0">back to Overall</option>
        <option value="1">m_some</option>
    </select>


    </form>
</body>
</html>
<script language="javascript" type="text/javascript">
    function setposition(svalue) {
        if (svalue == "0") {
            document.getElementById("t").options[1].selected = true;
        }
    }
</script>`enter code here`

您应该使用下面的ID,因为它们在DOM搜索中更容易。

<select name="t" id="t" onchange="this.form.submit();">
<option value="0">Overall</option>
<option value="1">t_name</option></select>
<select name="m" id="m" onchange="this.form.submit();">
<option value="0">back to Overall</option>
<option value="1">m_some</option></select>
<script>
$(function(){
  $('#m, #t').change(function(){
    //don't forget to trigger the change event
    if($('#m').val() == '0')
      $('#t').val('0').change();
      $('form#form_id').submit();   
  });
});
</script>

您可以这样做:

$(function(){
   $('[name="t"],[name="m"]').change(function(){
       if($(this).attr('name')=='m') && $(this).val()=='0'){
           $('[name="t"]').val('0');
       }
       $(this).closest('form').submit();
   });
});
$('select[name="m"]').change(function() {
    if($(this).val() == '0') {
        $('select[name="t"]').val('0');
    }
});

除此之外,您应该使用jQuery来设置onchange事件,而不是通过内联JS:来设置

$('select[name="t"], select[name="m"]').change(function() {
    $(this).closest('form').submit();
    // if you do not need any jquery submit events,
    // you can also use this.form.submit();
});

请参阅http://jsfiddle.net/ThiefMaster/NfVQZ/进行演示。