[英]How to use jQuery to select a dropdown option?
我想知道是否有可能在下拉框中获得 jQuery 到 select 一个<option>
,比如第 4 项?
<select>
<option></option>
<option></option>
<option></option>
<option></option>
<option></option>
</select>
我希望用户单击一个链接,然后让<select>
框更改其值,就好像用户通过单击<option>
选择了它一样。
怎么样
$('select>option:eq(3)').attr('selected', true);
例子:
$('select>option:eq(3)').attr('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select>
对于现代版本的 jquery,您应该使用.prop()
而不是.attr()
$('select>option:eq(3)').prop('selected', true);
例子:
$('select>option:eq(3)').prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select>
解决方案:
$("#element-id").val('the value of the option');
HTML select 元素具有selectedIndex
属性,可以写入该属性以选择特定选项:
$('select').prop('selectedIndex', 3); // select 4th option
使用纯 JavaScript 可以通过以下方式实现:
// use first select element
var el = document.getElementsByTagName('select')[0];
// assuming el is not null, select 4th option
el.selectedIndex = 3;
我会这样做
$("#idElement").val('optionValue').trigger('change');
最简单的方法是val(value)
函数:
$('select').val(2);
要获得选定的值,您无需提供任何参数:
$('select').val();
此外,如果您有<option value="valueToSelect">...</option>
,您可以执行以下操作:
$('select').val("valueToSelect");
如果您的选项有价值,您可以这样做:
$('select').val("the-value-of-the-option-you-want-to-select");
'select' 将是您选择的 ID 或类选择器。 或者如果只有一个选择,您可以使用示例中的标签。
如果要选择具有特定值的选项,请使用以下代码:
$('select>option[value="' + value + '"]').prop('selected', true);
Try with the below codes. All should work.
$('select').val(2);
$('select').prop('selectedIndex', 1);
$('select>option[value="5"]').prop('selected', true);
$('select>option:eq(3)').attr('selected', 'selected');
$("select option:contains(COMMERCIAL)").attr('selected', true);
对于 '' 元素,我们通常使用 'value' 属性。 这将使设置更容易:
$('select').val('option-value');
尝试这个:
$('#mySelectElement option')[0].selected = true;
问候!
我更喜欢 nth-child() 而不是 eq() 因为它使用基于 1 的索引而不是基于 0 的索引,这对我的大脑来说稍微容易一些。
//selects the 2nd option
$('select>option:nth-child(2)').attr('selected', true);
用身份证回答:
$('#selectBoxId').find('option:eq(0)').attr('selected', true);
$('select>option:eq(3)').attr('selected', 'selected');
这里的一个警告是,如果您有 javascript 监视选择/选项的更改事件,您需要添加.trigger('change')
以便代码变为。
$('select>option:eq(3)').attr('selected', 'selected').trigger('change');
因为只调用.attr('selected', 'selected')
不会触发事件
这对我有用:
$selectedindex=4
如果你想随机化选项,你总是可以做这样的事情:
$0selectedindex=Math.floor((Math.random()*($0.length-1)+1)
虽然第二个不在您的问题范围内,但它有助于说明如何应用/修改第一个作为请求。
var option = $("#dropdown").find("option:selected");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.