Set an option value as selected

后端 未结 2 1985
北荒
北荒 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 

    In HTML this gives :

    
    

    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/

提交回复
热议问题