Home >Web Front-end >JS Tutorial >The select drop-down box is selected by default

The select drop-down box is selected by default

php中世界最好的语言
php中世界最好的语言Original
2018-03-14 16:08:335710browse

This time I will bring you the select drop-down box that is selected by default. What are the precautions that are selected by default in the select drop-down box? The following is a practical case, let’s take a look.

This article mainly introduces the methods related to select drop-down box.

1. Get the value and text value of the drop-down box through id

For example:

<select class="form-control" id="numbers">
      <option value="1">数字1</option>
      <option value="2" selected>数字2</option>
</select>
$("#numbers option:selected").val(); 获取到下拉框被选中的optionde value值:2;
$("#numbers option:selected").text(); 获取到下拉框被选中的optionde 文本内容:数字2;

2. Select a select value by default: add the selected attribute

Enter a number in the input box, call the selectNumber() method when the focus is lost, and select the same number as in the input box

function selectNumber(){
var num = $("#num").val(); //获取input中输入的数字
var numbers = $("#numbers").find("option"); //获取select下拉框的所有值
for (var j = 1; j < numbers.length; j++) {
if ($(numbers[j]).val() == num) {
$(numbers[j]).attr("selected", "selected");
}
} 
}

I believe you have mastered the method after reading the case in this article, more Please pay attention to php Chinese websiteOther related articles for exciting content!

Recommended reading:

How to implement the toggle method in jQuery

How to use the select component in jquery


The above is the detailed content of The select drop-down box is selected by default. 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