i am working on a project, where i have to select a particular option of a select box, i know how to do this, but the problem is a function must be called whenever value of select box changes, when we do it manually it works, but when i do it with jquery onload, that function not works. Because it only work when a user manually change the option from select box. Please tell me how to do this.
example:
<select>
<option val="0" selected></option>
<option val="1"></option>
<option val="2"></option>
<option val="3"></option>
<option val="4"></option>
<option val="5"></option>
</select>
here is some of my efforts which i have tried:
$("select").val('5');
You wish to pre-select an option when the page first loads?
This bit of jQuery will find the option with the value of 5 and select it. By wrapping it in the jQuery(document).ready function it will run once the page has loaded.
jQuery(document).ready(function($){
$('select').find('option[value=5]').attr('selected','selected');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select>
<option value="0" selected>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Guess what, it is simple.
Your Select Component :
<select id="YourSelectComponentID">
<option value="0">Apple</option>
<option value="2">Banana</option>
<option value="3">Cat</option>
<option value="4">Dolphin</option>
</select>
Copy and paste this in your javaScript section.
$(function(){
document.getElementById("YourSelectComponentID").value = 4;
});
Now your option 4 will be selected whenever the page loads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With