我无法从jquery设置下拉列表的选定选项,我不确定问题是找到dropdrown还是代码问题。我尝试了所有不同的四种方式但没有结果。 HTML
<select class="form-control input-sm ddlFieldName" data-val="true" data-val-number="The field FieldTagNameId must be a number." data-val-required="The FieldTagNameId field is required." name="FieldName">
<option value="">----Select----</option>
<option value="1">Property Street Address 1</option>
<option value="2">Property Street Address 2</option>
<option value="3">Property City</option>
<option value="4">Property State Abbrev</option>
<option value="5">Property Zip Code</option>
</select>
我尝试过以下选项
var setValues;
$(document).ready(function(){
setValues = function(fieldName)
{
//1 st method
$('.ddlFieldName').val(fieldName);
$(".ddlFieldName > [value=fieldName]").attr("selected", "true");
//2. Method
jQuery(".ddlFieldName").find("option:contains(fieldName)").each(function()
{
if( jQuery(this).text() === fieldName )
{
jQuery(this).attr("selected","selected");
}
});
//3rd method
document.getElementById('.ddlFieldName').value = "fieldName";
// 4 method
$(".ddlFieldName > [value=" + fieldName + "]").attr("selected", "true");
}
});
&#13;
由于
答案 0 :(得分:1)
好的,我们将从方法编号4开始..您需要使用.filter()
和.prop("selected", true)
var setValues;
$(document).ready(function(){
setValues = function(fieldName)
{
// 4 method
$(".ddlFieldName > option").filter(function(){
return $(this).text() == fieldName
}).prop("selected", true);
}
setValues('Property City'); // run the function
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control input-sm ddlFieldName" data-val="true" data-val-number="The field FieldTagNameId must be a number." data-val-required="The FieldTagNameId field is required." name="FieldName">
<option value="">----Select----</option>
<option value="1">Property Street Address 1</option>
<option value="2">Property Street Address 2</option>
<option value="3">Property City</option>
<option value="4">Property State Abbrev</option>
<option value="5">Property Zip Code</option>
</select>
&#13;
使用方法编号2
var setValues;
$(document).ready(function(){
setValues = function(fieldName)
{
// 2 method
$(".ddlFieldName > option:contains("+fieldName+")").prop("selected", true);
}
setValues('Property City'); // run the function
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control input-sm ddlFieldName" data-val="true" data-val-number="The field FieldTagNameId must be a number." data-val-required="The FieldTagNameId field is required." name="FieldName">
<option value="">----Select----</option>
<option value="1">Property Street Address 1</option>
<option value="2">Property Street Address 2</option>
<option value="3">Property City</option>
<option value="4">Property State Abbrev</option>
<option value="5">Property Zip Code</option>
</select>
&#13;