JQuery - how to select dropdown item based on value

前端 未结 13 2027
[愿得一人]
[愿得一人] 2020-12-04 17:18

I want set a dropdown(select) to be change based on the value of the entries.

I have


                        
    
提交评论

  • 2020-12-04 17:42

    May be too late to answer, but at least some one will get help.

    You can try two options:

    This is the result when you want to assign based on index value, where '0' is Index.

     $('#mySelect').prop('selectedIndex', 0);
    

    don't use 'attr' since it is deprecated with latest jquery.

    When you want to select based on option value then choose this :

     $('#mySelect').val('fg');
    

    where 'fg' is the option value

    0 讨论(0)
  • 2020-12-04 17:45
    $('#yourdropddownid').val('fg');
    

    Optionally,

    $('select>option:eq(3)').attr('selected', true);
    

    where 3 is the index of the option you want.

    Live Demo

    0 讨论(0)
  • 2020-12-04 17:50

    $('#dropdownid').val('selectedvalue');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id='dropdownid'>
        <option value=''>- Please choose -</option>
        <option value='1'>1</option>
        <option value='2'>2</option>
        <option value='selectedvalue'>There we go!</option>
        <option value='3'>3</option>
        <option value='4'>4</option>
        <option value='5'>5</option>
    </select>

    0 讨论(0)
  • 2020-12-04 17:51

    You can use this jQuery code which I find it eaiser to use:

    $('#your_id [value=3]').attr('selected', 'true');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <select id="your_id" name="name" class="form-control input-md">
      <option value="1">Option #1</option>
      <option value="2">Option #2</option>
      <option value="3">Option #3</option>
      <option value="4">Option #4</option>
      <option value="5">Option #5</option>
      <option value="6">Option #6</option>
      <option value="7">Option #7</option>
    </select>

    0 讨论(0)
  • 2020-12-04 17:51

    This code worked for me:

    $(function() {
        $('[id=mycolors] option').filter(function() { 
            return ($(this).text() == 'Green'); //To select Green
        }).prop('selected', true);
    });
    

    With this HTML select list:

    <select id="mycolors">
          <option value="1">Red</option>
          <option value="2">Green</option>
          <option value="3">Blue</option>
    </select>
    
    0 讨论(0)
  • 提交回复
    热议问题