问题
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.
How can I do that?
回答1:
When the page loads run this (you can put it in <body onload="//put code here">
):
$("option[value='10']").attr('selected','selected');
回答2:
Test the example: 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:
<select id='mySelectBox'>
<option value='5'>5</option>
<option value='10' selected='selected'>10</option>
<option value='15'>15</option>
</select>
回答3:
Above code is working you can use following code:
$("option[value='10']").attr('selected','selected');
回答4:
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:
<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)
$(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);
}
});
回答5:
In the latest jQuery version this works for me:
$("option[value='10']").prop('selected',true);
来源:https://stackoverflow.com/questions/3106473/how-to-preselect-option-in-select-box-using-jquery