我如何,使用jQuery,为“选择”的目标已选定项目的“下一个”项目
举例来说,如果我有:
<select>
<option value="1" >Number 1</option>
<option value="2" selected="selected">Number 2</option>
<option value="3" >Number 3</option>
<option value="4" >Number 4</option>
</select>
我们可以看到,“2号”被选中,并使用jQuery,我想作为选择设置为“3号”,并从“2号”删除选中的“属性”。 我假设我需要使用的下一个选择,但我不太清楚如何实现。
Answer 1:
$('option:selected', 'select').removeAttr('selected').next('option').attr('selected', 'selected');
看看这里的工作代码http://jsbin.com/ipewe/edit
Answer 2:
更新:
在jQuery的1.6+你应该使用prop()
代替attr()
在这种情况下。
属性和性能之间的差异可以在特定情况下非常重要。 jQuery的1.6之前,.attr()方法有时把属性值考虑检索某些属性,这可能会导致不一致的行为时。 在jQuery 1.6的,所述.prop()方法提供了一种方式,以明确地检索属性值,而.attr()获取属性。
var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);
原来的答案:
如果你想通过选项的值来选择,无论其位置,(这个例子假设你有你的选择一个ID):
var theValue = "whatever";
$("#selectID").val( theValue ).attr('selected',true);
你并不需要“取消选择”。 当您选择另一种自动发生。
Answer 3:
从1.6.1版本,它的最好使用布尔属性/属性,如选择的方法道具,只读启用,...
var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);
欲了解更多信息,请参阅到http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/
Answer 4:
您可以使用
$('option:selected').next('option')
要么
$('option:selected + option')
并设定值:
var nextVal = $('option:selected + option').val();
$('select').val(nextVal);
Answer 5:
如果你想选择指定的ID:
$("#nextPageLink").click(function(){
$('#myselect option:selected').next('option').attr('selected', 'selected');
$("#myselect").change();
});
如果你点击ID为“nextPageLink”项目,下一个选项将被选中的onChange()事件将被调用。 它可能是这样的:
$("#myselect").change(function(){
$('#myDivId').load(window.location.pathname,{myvalue:$("select#myselect").val()});
});
的OnChange()事件使用Ajax加载的东西到指定的DIV。
window.location.pathname =实际地址
定义的OnChange()事件,因为它allowes你不仅使用NETX /上一个按钮,而是直接使用标准的选择来改变值。 如果值被改变,页面确实somethig自动。
Answer 6:
这就是我刚才所用,我喜欢它是如何:-)干净
$('select').val(function(){
var nextOption = $(this).children(':selected').next();
return $(nextOption).val();
}).change();
Answer 7:
$('your_select option:selected').next('option').prop('selected', true)
Answer 8:
$('#next').click( function(){
$('#colored_background option:selected').next('option').attr('selected', 'selected');
changeBackgroundColor();
});
在工作什么是我最喜欢的颜色? 。 点击箭头。
Answer 9:
查找的行,然后
var row = $('#yourTable');
你要选择的值
var theValue = "5";
row.find("select:eq(2)").find("option[value="+theValue+']').attr('selected','selected');
Answer 10:
$("select").prop("selectedIndex",$("select").prop("selectedIndex")+1)
Answer 11:
$('#my_sel').val($('#my_sel option:selected').next().val());
$('#my_sel').val($('#my_sel option:selected').prev().val());
文章来源: jQuery Set Selected Option Using Next