jQuery 如何使用jQuery在选择框中预选选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3106473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to preselect option in select box using jQuery
提问by user113716
I have one select box with various options.
我有一个带有各种选项的选择框。
When a page loads then one option with a value, for example 10, should be preselected with jQuery.
当页面加载时,应使用 jQuery 预选一个带有值的选项,例如 10。
How can I do that?
我怎样才能做到这一点?
回答by Adam
When the page loads run this (you can put it in <body onload="//put code here">
):
当页面加载时运行这个(你可以把它放在<body onload="//put code here">
):
$("option[value='10']").attr('selected','selected');
回答by user113716
Test the example:http://jsfiddle.net/VArCZ/
测试示例:http : //jsfiddle.net/VArCZ/
$(document).ready(function() {
$('#mySelectBox').val('10');
});
Although, jQuery wouldn't be required for this if the intial value will be static:
虽然,如果初始值是静态的,则不需要 jQuery:
<select id='mySelectBox'>
<option value='5'>5</option>
<option value='10' selected='selected'>10</option>
<option value='15'>15</option>
</select>?
回答by Kevin Lieser
In the latest jQuery version this works for me:
在最新的 jQuery 版本中,这对我有用:
$("option[value='10']").prop('selected',true);
回答by purab
Above code is working you can use following code:
上面的代码正在运行,您可以使用以下代码:
$("option[value='10']").attr('selected','selected');
回答by daviek19
This is something I re-use in my code. Hope it be of help. You can enable the console output to see whats happening. With this function you can either match the desired option based on the option value or option text as shown in the example below.
这是我在代码中重复使用的东西。希望它有帮助。您可以启用控制台输出以查看发生了什么。使用此功能,您可以根据选项值或选项文本匹配所需的选项,如下例所示。
The Html:
Html:
<select id="languages">
<option value="01">JAVA</option>
<option value="02">HTML</option>
</select>
<select class="data-interchange">
<option value="A">JSON</option>
<option value="B">XML</option>
</select>
The JavaScript (Using Jquery)
JavaScript(使用 Jquery)
$(function() {
preSelectDropDownList("#languages", "val", "02");
preSelectDropDownList(".data-interchange", "text", "XML");
function preSelectDropDownList(selector, checkAgaints, neddle) {
//console.log(selector, checkAgaints, neddle);//DEBUG
let hayStack = "";
neddle = neddle == null ? "" : neddle;
$(selector + " option").filter(function() {
if (checkAgaints === "text") {
hayStack = $(this).text();
} else if (checkAgaints === "val") {
hayStack = $(this).val();
} else {
alert("Error on Param 2.Only text or value allowed -->" + checkAgaints);
}
var result = hayStack.includes(neddle);
//console.log(neddle+" vs "+hayStack+" = "+result);//DEBUG
//console.log("Selected return", result);//DEBUG
return result;
}).prop('selected', true);
}
});