Search code examples
jqueryselectdrop-down-menuhtml-select

Set an option from the dropdown when page loads in jquery


I have the following html:

<select id="id_visit_number" name="visit_number">
  <option value="" selected="selected">---------</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
</select>

When the page is opened / loaded, I want the default option to be selected as Two. So I tried the code below, but was not working

<script type='text/javascript">

        $( document ).ready(function() {
                $("select #id_visit_number option").filter(function() {
                    return $(this).val() == "2"; 
                }).prop('selected', true);
        });        
        </script>

How do I make an option selected by default when the page loads?


Solution

  • No need to give space. because that id in select dropdownlist

    change

    $("select #id_visit_number option")
    

    to

    $("select#id_visit_number option")