jQuery Loop through selects and set selected option

后端 未结 3 690
不思量自难忘°
不思量自难忘° 2021-01-29 14:05

I\'d like to loop through all of the select inputs on a page and if the selected value is not a certain option then set that value to selected

I have some selects

<
相关标签:
3条回答
  • 2021-01-29 14:15

    Find all options with value equal to 2 and select them:

    $('select').each(function() {
      $(this).find('option[value="2"]').prop('selected', true);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <select name="select1">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3" selected>Three</option>
      <option value="4">Four</option>
      <option value="5">Five</option>
    </select>
    
    <select name="select2">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
      <option value="4">Four</option>
      <option value="5">Five</option>
    </select>
    
    <select name="select3">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
      <option value="4">Four</option>
      <option value="5">Five</option>
    </select>

    0 讨论(0)
  • 2021-01-29 14:16

    You can pass the desired option value to .val() method while targeting select to select required option element:

    $('select').val('2');
    

    Working Snippet:

     $('select').val('2');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <select name="select1">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3" selected>Three</option>
      <option value="4">Four</option>
      <option value="5">Five</option>
    </select>
    
    <select name="select2">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
      <option value="4">Four</option>
      <option value="5">Five</option>
    </select>
    
    <select name="select3">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
      <option value="4">Four</option>
      <option value="5">Five</option>
    </select>

    0 讨论(0)
  • 2021-01-29 14:32

    You can explore the value key of this jquery object

       $('select').each(function() {
        var selected = $(this)[0].value;
        console.log(selected)
        if (selected != 2) {
            alert("Not 2")
    
       }
    })
    

    JSFIDDLE

    0 讨论(0)
提交回复
热议问题