Skip to content Skip to sidebar Skip to footer

Selecting An Option Is Resetting Another Depending Selection Box

I have two selection (city, building) is the dependent on what the users choose for state.

Solution 1:

Here is the relevant code that is "resetting" the city and building checkboxes:

$('form').on("change", "select", function(){
    var current_index = $(this).index();
    if($(this).eq(current_index).val() == 'Z') {
    } else {
        current.siblings('.city option:first').attr('selected', 'selected');
        current.siblings('.building option:first').attr('selected', 'selected');
    }
});

So any time you change ANY dropdown, as long as the value isn't Z, you are setting the city and state to the first option.


Instead of doing $('form').on("change", "select", function(){}) and then if statements for each input, why don't you monitor the change event for each input directly:

<select id="selState" name="State"class="state">
  <option selected disabled>Choose a State</option>
  <option value="1">California</option>
  <option value="2">New York</option>
</select>
<select id="selCity" name="City"class="city" disabled="true">
  <option value="Z">Select a city</option>
</select>
<select id="selBuilding" name="Building"class="building" disabled="true">
  <option value="Z">Select a building</option>
</select>

If you want to populate the city and building dropdowns based on the state dropdown, and do nothing when the city and building dropdowns are changed, you would do something like this:

$('form').on("change", "#selState", function(){
  //get state idvar stateid = $(this).val();
  //Get cities for selected state
  $.getJSON('get_city/', {state_id: stateid}, function(data) {
    //add "Select a city option"
    $('#selCity').html('<option value="Z">Select a city</option>');
    //Loop through returned cities.for(var i=0; i<data.length; i++){
      //add city to select
      $('#selCity').append('<option value="'+data[i].pk+'">'+data[i].fields['name']+'</option>');
    }
  });
  //Get buildings for selected state
  $.getJSON('get_building/', {state_id: stateid}, function(data) {
    //add "Select a building option"
    $('#selCity').html('<option value="Z">Select a building</option>');
    //Loop through returned buildings.for(var i=0; i<data.length; i++){
      //add building to select
      $('#selBuilding').append('<option value="'+data[i].pk+'">'+data[i].fields['name']+'</option>');
    }
  });
  //enable other select
  $('#selCity').attr('disabled', false);
  $('#selBuilding').attr('disabled', false);
})

Post a Comment for "Selecting An Option Is Resetting Another Depending Selection Box"