根据下拉菜单更改其他选项

时间:2014-01-14 02:39:53

标签: jquery html html-select

我想做的是根据一个特定选择的答案自动更改其他下拉菜单选项下拉列表。在这种情况下,当主下拉列表更改为“更改”时,我希望其他下拉列表找到“拒绝回答”选项。 (http://jsfiddle.net/sNZ5X/

HTML

<h3>Main Select Dropdown
    <select id="master">
        <option>Do Nothing</option>
        <option>Change</option>
    </select>
</h3>
<hr>
<p class="important">Question 1
    <select class="rta">
        <option>Answer 1</option>
        <option>Answer 2</option>
        <option>Refused to Answer</option>
    </select>
</p>
<p class="required">Question 2
    <select class="rta">
        <option>Answer 1</option>
        <option>Answer 2</option>
        <option>Refused to Answer</option>
    </select>
</p>

JS

$( "#master" )
  .change(function () {
    var str = "Refusted to Answer";
    if $(master).selected = "Change"
    $( ".rta" ).change( str );
  })
  .change();

2 个答案:

答案 0 :(得分:2)

done, heres the FIDDLE

基本上,您需要正确测试值,并正确设置所选值。你的“拒绝回答”的字符串拼写错误,永远不会匹配。

$('#master').on('change', function() {
    if (this.value == 'Change') {
        $('.rta').val('Refused to Answer');
    }

});

答案 1 :(得分:1)

您的脚本存在一些问题(请务必检查您的浏览器控制台):

  1. master未定义。我想你的意思是$('#master')而不是$(master)
  2. .selected不是有效的方法。
  3. =用于分配。使用==进行比较
  4. 无效的if声明 - 使用括号;)
  5. 以下是JSFiddle上的工作示例:

    $( "#master" )
      .change(function () {
          if ($('#master option:selected').val() == "Change")
              // Assuming that last child is always 'Refused to answer'
              $('.rta option:last-child').prop('selected', true);
      })
      .change();