Jquery 在html下拉列表中设置默认值
我正在尝试设置dropdown的默认值,但我没有这样做。请告诉我这个代码有什么问题Jquery 在html下拉列表中设置默认值,jquery,html,jsp,Jquery,Html,Jsp,我正在尝试设置dropdown的默认值,但我没有这样做。请告诉我这个代码有什么问题 <span>Section Name:</span><select id="editSection" name="classSection" > <option >A</option><option >B</option><option >C</option><option >D</opt
<span>Section Name:</span><select id="editSection" name="classSection" >
<option >A</option><option >B</option><option >C</option><option >D</option>
</select><br>
我正在尝试将秒设置为下拉列表的默认值。sec是一个变量,它是在多次操作之后获得的,其值将是a、B、C、D。$(“#editSection”).empty().append(“--Select-->”).append($.trim(sec));
$("#editSection").empty().append("<option value='0'>--Select--</option>").append($.trim(sec));
尝试下面的javascript代码
var theText="B";
$("#editSection option").each(function() {
if($(this).text() == theText) {
$(this).attr('selected', 'selected');
}
});
<选项>文本与文本变量相同,选项将被选择。 尝试使用id。a <代码>选择< /COD>和<代码>输入< /代码>不考虑相同类型的元素。
我找到了一个很好的解释。建议使用:
//for example let your sec variable be "C".
var sec = "C";
// it does the trick, and set default to sec's value.
$("select option:contains("+ $.trim( sec ) + ")").prop('selected',true);
节名:
A.
B
C
D
var sec=“C”;
$('#editSection选项')。每个(函数(){
if($(this).text()=秒){
警报($(this.val());
$(this.attr('selected','selected');
}
});
$('#editSection').val($.trim(sec));
//for example let your sec variable be "C".
var sec = "C";
// it does the trick, and set default to sec's value.
$("select option:contains("+ $.trim( sec ) + ")").prop('selected',true);
<span>Section Name:</span>
<select id="editSection" name="classSection" >
<option >A</option>
<option >B</option>
<option >C</option>
<option >D</option>
</select><br>
var sec = "C";
$('#editSection option').each(function() {
if ($(this).text() == sec){
alert($(this).val());
$(this).attr('selected', 'selected');
}
});