Home > Web Front-end > JS Tutorial > 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
Release: 2024-11-04 21:06:02
Original
954 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template