Sikander Sikander - 29 days ago 11
Javascript Question

Jquery : Change Dropdown value on change event

i have a dropdown like this

<div class="form-group">
<select class="form-control" id="class" name="class">
<option value="grade">Grade</option>
<option value="year">Year</option>
</select>
</div>


And there is another drop-down next to it

<div class="form-group">
<select class="form-control" id="class_year" name="class_year" >
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option
</select>
</div>


if in first dropdown grade is selected the second dropdown should start from 3 otherwise it should start from 5 . i tried using
on('change'function(){})
but could not manipulate values , Please help me with this

here i want to change the value :

$("#class").on('change',function(){
if(this.value=='grade'){
// here i have to set the value, if its grade it will start from 4 otherwise it will be 3
}
})

Answer Source

$('.first-select').on('change', function() {
     if(this.value == 'grade') {
         $('.second-select option').show();
          $('.second-select').prop('selectedIndex',0);
     }
     else if(this.value == 'year') {
         $('.second-select option[value="4"]').hide();
         $('.second-select option[value="3"]').hide();
         $('.second-select').prop('selectedIndex',2);
     }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="form-group">
     <select class="form-control first-select" id="class" name="class">
         <option value="grade">Grade</option>
         <option value="year">Year</option>
     </select>
 </div>
 
 
 <div class="form-group">
     <select class="form-control second-select" id="class_year" name="class_year"  >
         <option value="3">3</option>
         <option value="4">4</option>
         <option value="5">5</option>
         <option value="6">6</option>
         <option value="7">7</option>
         <option value="8">8</option 
     </select>
 </div>