我想知道是否有可能让jQuery<option>
在下拉框中选择,例如第4个项目?
<select>
<option></option>
<option></option>
<option></option>
<option></option>
<option></option>
</select>
我希望用户单击一个链接,然后让该<select>
框更改其值,就像用户通过单击选中它一样<option>
。
怎么样
$('select>option:eq(3)').attr('selected', true);
http://www.jsfiddle.net/gaby/CWvwn/中的示例
对于现代版本的jquery,应使用.prop()
代替.attr()
$('select>option:eq(3)').prop('selected', true);
例如在http://jsfiddle.net/gaby/CWvwn/1763/
解决方案:
$("#element-id").val('the value of the option');
HTML select elements have a selectedIndex
property that can be written to in order to select a particular option:
$('select').prop('selectedIndex', 3); // select 4th option
Using plain JavaScript this can be achieved by:
// 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');
如果您的选择具有价值,则可以执行以下操作:
$('select').val("the-value-of-the-option-you-want-to-select");
“选择”将是您选择的ID或类选择器。或者,如果只有一个选择,则可以使用示例中的标记。
The easiest way is val(value)
function:
$('select').val(2);
And to get the selected value you give no arguments:
$('select').val();
Also, you if you have <option value="valueToSelect">...</option>
, you can do:
$('select').val("valueToSelect");
Use the following code if you want to select an option with a specific value:
$('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);
I prefer nth-child() to eq() as it uses 1-based indexing rather than 0-based, which is slightly easier on my brain.
//selects the 2nd option
$('select>option:nth-child(2)').attr('selected', true);
With '' element usually we use 'value' attribute. It will make it easier to set then:
$('select').val('option-value');
Try this:
$('#mySelectElement option')[0].selected = true;
Regards!
answer with id:
$('#selectBoxId').find('option:eq(0)').attr('selected', true);
$('select>option:eq(3)').attr('selected', 'selected');
One caveat here is if you have javascript watching for select/option's change event you need to add .trigger('change')
so the code become.
$('select>option:eq(3)').attr('selected', 'selected').trigger('change');
because only calling .attr('selected', 'selected')
does not trigger the event
这对我有用:
$selectedindex=4
如果要随机化选项,则可以始终执行以下操作:
$0selectedindex=Math.floor((Math.random()*($0.length-1)+1)
虽然第2个项目符号不在您的问题范围内,但它可以说明第1个项目符号如何根据要求进行应用/修改。
文章标签:drop-down-menu , html , html-select , javascript , jquery
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!