Home > Web Front-end > JS Tutorial > How to Select an Option in a Dropdown by Text Description with jQuery?

How to Select an Option in a Dropdown by Text Description with jQuery?

DDD
Release: 2024-11-03 12:53:03
Original
1032 people have browsed it

How to Select an Option in a Dropdown by Text Description with jQuery?

How to Set Selected Value in Select Control Using Text Description with jQuery

When working with select controls in your web application, you may encounter situations where you need to set the selected element based on its text description rather than its value. While setting the value is straightforward using jQuery's val() method, selecting by text description requires a different approach.

In jQuery versions 1.6 and above, you can use the following code snippet to achieve this:

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

This code selects all the options within the select control and filters them based on their text. The filter function compares each option's text to the provided text1 value. Once the matching option is found, its selected property is set to true.

For example, consider the following select control:

<code class="html"><select>
  <option value="0">One</option>
  <option value="1">Two</option>
</select></code>
Copy after login

If you want to select the option with the text "Two" using jQuery, you can use the above code snippet along with the following code:

<code class="html"><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>
Copy after login

This will result in the "Two" option being selected in the drop-down list.

The above is the detailed content of How to Select an Option in a Dropdown by Text Description with 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template