Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the selected option of a select box onload?

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');
like image 851
Amrinder Singh Avatar asked Oct 23 '25 19:10

Amrinder Singh


2 Answers

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>
like image 76
Richard Parnaby-King Avatar answered Oct 26 '25 10:10

Richard Parnaby-King


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.

like image 35
Majid Ali Khan Avatar answered Oct 26 '25 10:10

Majid Ali Khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!