Jquery controls that the text and value of the select is selected

  • 2020-03-30 03:08:05
  • OfStack

Every time the operation of select, always want to turn over on the Internet, too tedious, their summary here.

Such as < Select the class = "selector" > < / select>

1. Select the items with value of "all"
 
$(".selector").val(" all "); 

2. Set text to "all"
 
$(".selector").find("option[text=' all ']").attr("selected",true); 

There is a use of brackets, in which the equal sign is preceded by the property name, without quotation marks. In many cases, the use of brackets makes the logic simple.

3. Get the value of the currently selected item
 
$(".selector").val(); 

4. Gets the text of the currently selected item
 
$(".selector").find("option:selected").text(); 

The colon is used here. Knowing how to use it and drawing inferences from it will also make the code cleaner.

A lot of times you use a cascade of select, where the value of the second select changes as the value of the first select is selected. This is very simple in jquery.

Such as:
 
$(".selector1").change(function(){ 

//So let's clear the second one

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

//In practice, this option usually generates multiple options in a loop

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

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

}); 

Related articles: