Set an option value as selected

后端 未结 2 1986
北荒
北荒 2020-12-31 23:02

I would like to load a select box where in the user\'s selected value will automatically appear.

I am receiving a Json data from the server with the user info. sampl

相关标签:
2条回答
  • 2020-12-31 23:27

    after much research, I finally went back to see the jQuery documentation that gave me the right answer :

    1 / Delete all the attributes of tags that are already with the 'selected' attribute

    function remove_selected(){
      $("select option").removeAttr('selected');
    }
    

    2 / I use the prop() function of jQuery to assign the 'selected' attribute to the desired tag

    // USE THE FUNCTION TO REMOVE ALL ATTRIBUTES ALREADY SELECTED  
    remove_selected();
    
    // Set the tag <option> attribute to 'selected'
    $('select option[value="ThatYouWant"]').prop({defaultSelected: true});
    

    In HTML this gives :

    <select>
      <option value="something">Something</option>
      <option value="ThatYouWant" selected>That you want</option>
      <option value="OtherValue">Other value</option>
    </select>
    

    It is clean and without burrs, thank you for your feedback and corrections, approve if you find this solution correct. Sincerely, Raf.

    Source : https://api.jquery.com/prop/

    0 讨论(0)
  • 2020-12-31 23:31

    As you've tagged this question with jQuery you can just set the val() on the select directly:

    var user_color = 'red'; //data[2].color;
    $('#input_user').val(user_color);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="input_user" class="selectinput" disabled="true">
      <option value="n/a">n/a</option>
      <option value="red">red</option>
      <option value="green">green</option>
      <option value="yellow">yellow</option>
      <option value="blue">blue</option>
      <option value="white">white</option>
    </select>

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