1

I have a form with 2 drop down lists on the same page using the same ids.

<select id="country">
  <option value="">Any</option>
  <option value="ENGLAND">England</option>
  <option value="IRELAND">Ireland</option>
  <option value="SCOTLAND">Scotland</option>
  <option value="WALES">Wales</option>
</select>

<select id="county">
  <option value="">Select a country first...</option>
</select>

<div style="clear:both">&nbsp;</div>

<select id="country">
  <option value="">Any</option>
  <option value="ENGLAND">England</option>
  <option value="IRELAND">Ireland</option>
  <option value="SCOTLAND">Scotland</option>
  <option value="WALES">Wales</option>
</select>

<select id="county">
  <option value="">Select a country first...</option>
</select>

Not sure how to I change the JavaScript code so the second county drop down list functions same as the first one. The existing javascript and how it functions can be seen here:

http://jsfiddle.net/pfYEb/10/

4

2 回答 2

3

You'll probably want to use class="country" instead of id="country" so that your selector will match both. (same for your id="county") In your jsfiddle, you'll also need to distinguish which county to change within your country change event. One easy way to do this is to use the index of the current element.

I've forked your jsfiddle here.

HTML

<select class="country">
  <option value="">Any</option>
  <option value="ENGLAND">England</option>
  <option value="IRELAND">Ireland</option>
  <option value="SCOTLAND">Scotland</option>
  <option value="WALES">Wales</option>
</select>

<select class="county">
  <option value="">Select a country first...</option>
</select>

<div style="clear:both">&nbsp;</div>

<select class="country">
  <option value="">Any</option>
  <option value="ENGLAND">England</option>
  <option value="IRELAND">Ireland</option>
  <option value="SCOTLAND">Scotland</option>
  <option value="WALES">Wales</option>
</select>

<select class="county">
  <option value="">Select a country first...</option>
</select>
​

Relevant Javascript:

  $('.country').change(function() {
    var country = $(this).val(),
        county  = $('.county').eq($(".country").index(this)); // This matches the county

    // Empty county dropdown
    county.empty();

    // Update dropdown with appropriate contents
    if (country === '') {
      county.append('<option value="">Select a country first...</option>');
    } else {
      $.each(counties[country], function(i, v) {
        county.append('<option value="' + i + '">' + v + '</option>');  
      });
    }
  });
于 2012-12-02T00:16:43.093 回答
2

You can't really solve this querying by id. Element ID's have to be unique within a document by specification by the way. Your best shot, use classes instead.

于 2012-12-02T00:16:31.700 回答