同步2选择框

时间:2013-08-07 20:35:49

标签: javascript jquery html-select

我有两个选择框:

<select name="county" id="countyselect">
 <option value="Dixie">Dixie</option>
 <option value="Hernando">Hernando</option>
 <option value="Holmes">Holmes</option>
 <option value="Jackson">Jackson</option>
 <option value="Liberty">Liberty</option>
 <option value="Putnam">Putnam</option>
</select>
<select name="site" id="siteselect">
 <option value="Florahome">Florahome</option>
 <option value="Green Swamp">Green Swamp</option>
 <option value="NE Jackson County">NE Jackson County</option>
 <option value="N Holmes County">N Holmes County</option>
 <option value="S Liberty County">S Liberty County</option>
 <option value="Suwannee">Suwannee</option>
</select>

当更改一个框时,另一个框需要更改为相应的索引(即,如果在“县”中选择了Dixie,则应在“站点”中选择Florahome)。我使用jQuery的尝试如下,但似乎没有用。

$('select#countyselect').change(function() {
    var countySelector = $('select#countyselect').attr("selectedIndex"); 
    $('select#siteselect').attr('selectedIndex', countySelector);
});
$('select#siteselect').change(function() {
    var siteSelector = $('select#siteselect').attr("selectedIndex");
    $('select#countyselect').attr('selectedIndex', siteSelector);
});

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您需要prop,而不是attr。类似的东西:

function matchUp(selected, toselect)
{
  var idx = selected.prop('selectedIndex');
  toselect.prop('selectedIndex', idx);
}


$('#countyselect').change(
  function() {
    matchUp($('#countyselect'), $('#siteselect'));
  }
);

$('#siteselect').change(
  function() {
    matchUp($('#siteselect'), $('#countyselect'));
  }
);

在此处采取行动:http://codepen.io/paulroub/pen/phmaJ