In the realm of web development, selecting an element within a select control based on its text description often arises. While setting an option by its value is straightforward, finding the corresponding value for a given text description can be a challenge.
The need for this functionality stems from the situation where a JavaScript variable holds a text string, and the aim is to select the drop-down option whose text matches this string. Unlike the value-based selection, which utilizes the $("#my-select").val(myVal) syntax, this task requires a more intricate approach.
For jQuery versions 1.6 and above, the solution lies in leveraging the filter() and prop() methods. The filter() method sifts through all options within the select control, comparing their text descriptions to the desired string. The resulting element is then targeted by the prop() method, setting its selected attribute to true.
Consider a select control with two options: 'One' and 'Two'. The following code illustrates how to select the option with the text 'Two' using the text-based approach:
<code class="javascript">var text1 = 'Two'; $("select option").filter(function() { //may want to use $.trim in here return $(this).text() == text1; }).prop('selected', true);</code>
This code effectively selects the 'Two' option within the drop-down list based on its text description, even without knowing its value.
The above is the detailed content of How to Select a Drop-Down Option by Its Text Description with jQuery?. For more information, please follow other related articles on the PHP Chinese website!