Home >Web Front-end >JS Tutorial >How Can I Set the Selected Value of a Select Control by Text Description Using jQuery?
jQuery: Setting the Selected Value of a Select Control by Text Description
In this scenario, you want to set the selected value of a select control using jQuery based on its text description instead of its value. While setting it by value is straightforward using $("#my-select").val(myVal), you seek a method for doing so via the text description.
For jQuery versions 1.6 and above, you can leverage the following approach:
<code class="js">var text1 = 'Two'; $("select option").filter(function() { // May want to use $.trim in here return $(this).text() == text1; }).prop('selected', true);</code>
This solution utilizes the filter function to select the option element with the matching text by traversing its text nodes. It then sets the selected property of the matching element to true, effectively setting it as the selected option.
The above is the detailed content of How Can I Set the Selected Value of a Select Control by Text Description Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!