Home  >  Article  >  Web Front-end  >  How to Select an Option in a Select Control by Text Description Using jQuery?

How to Select an Option in a Select Control by Text Description Using jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 21:06:02907browse

How to Select an Option in a Select Control by Text Description Using jQuery?

How to Set Selected Option in a Select Control Based on Its Text Description with jQuery

Selecting an option in a select control by its value is a fairly straightforward task in jQuery. However, if you need to set the selected element based on its text description, the process can be slightly more complex.

Using jQuery v1.6

For jQuery versions 1.6 and above, you can use the following code to set the selected option by its text:

<code class="js">var text1 = 'Two';
$("select option").filter(function() {
  return $(this).text() == text1;
}).prop('selected', true);</code>

This code snippet first uses the filter() method to select the option element with the matching text description (in this case, "Two"). It then sets the selected property of the selected option to true, effectively marking it as the selected option.

The above is the detailed content of How to Select an Option in a Select Control by Text Description Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn