Home >Web Front-end >JS Tutorial >How to set select in javascript

How to set select in javascript

青灯夜游
青灯夜游Original
2021-04-08 16:33:5315965browse

Method: 1. First obtain the select element; then use the val() method to select the select option with the specified value. 2. First get the element; then use the find() method to find the select option with the specified text value; finally use the "attr("selected",true)" method to select it.

How to set select in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

javascript settings select selected

For example

<select class="selector"></select>

1. Set the item with value to pxx selected

$(".selector").val("pxx");

2. Select the item with text set to pxx

$(".selector").find("option[text=&#39;pxx&#39;]").attr("selected",true);

There is a usage of brackets. The equal sign in the brackets is preceded by the attribute name. No need to add quotes. Many times, the use of square brackets can make logic very simple.

The colon is used here. Mastering its usage and drawing inferences will also make the code simpler.

Many times the cascade of selects is used, that is, the value of the second select changes with the value selected by the first select. This is very simple in jquery.

$(".selector1").change(function(){ 

// 先清空第二个 

$(".selector2").empty(); 

// 实际的应用中,这里的option一般都是用循环生成多个了 

var option = $("<option>").val(1).text("pxx"); 

$(".selector2").append(option); 

});

Recommended learning: javascript advanced tutorial

The above is the detailed content of How to set select in javascript. 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