Skip to content Skip to sidebar Skip to footer

How To Change Select Tag Value When Other Select Is Change?

My HTML page contents two select options as follows. It has two li selection as #age1 and #age2 with contents 18 to 30 ages. I want to make it as if user select a age from #age1,

Solution 1:

$("#age1").change(function() {
    var getStartVal = $(this).val();
    $("#age2").val(getStartVal).find("option").show().each(function() {
      if($(this).attr("value")<getStartVal) {
         $(this).hide();
      }
  });
});

You can use the above jquery to make it working.

Working Fiddle : https://jsfiddle.net/wpam11k7/


Solution 2:

ameenulla0007 answer is a good one but I would edit you html like this

<select id="age1">
    <option value="18">18</option><option value="19">19</option>
    <option value="20">20</option><option value="21">21</option>
    <option value="22">22</option><option value="23">23</option>
    <option value="24">24</option><option value="25">25</option>
    <option value="26">26</option><option value="27">27</option>
    <option value="28">28</option><option value="29">29</option>
    <option value="30">30</option>
  </select>
  <label class="label">To</label>
  <select id="age2">

  </select>
</li>

Then use this jQuery to add just the selections you want rather than hiding

jQuery("#age1").change(function() {      

    var bottomEnd = jQuery("#age1").val();
    var topEnd = jQuery("#age1").val() + 30;
    for( $i=bottomEnd; $i < topEnd; $i++ {
        jQuery('#age-2').append('<option value="'+jQuery('#age1').val()+'">'+jQuery('#age1').val()+'</option>');
    }
});

Solution 3:

You could just use the html from your first age list to populate the second one, since they appear to be the same:

$("#age1").on("change", function() {

  /* get the value of age1 */
    var val = $(this).val();

  /* get all the ages after the selected one
     and add them to the selected age */
  var $selected = $(this).find("option:selected");
  var $available = $selected.add( $selected.nextAll() ).clone();

  /* save the selected value of age2 */
  var selected2 = $("#age2").find("option:selected").val();

  /* append the html from age1 selection to the
    age2 list, and try to keep the old selection value */
  $("#age2")
    .html( $available )
    .find("option[value='" + selected2 + "']")
    .prop("selected", true);

});

You can see it running here; https://jsfiddle.net/1qsnzyjh/ :)


Post a Comment for "How To Change Select Tag Value When Other Select Is Change?"