2012-07-19 173 views
19

我正在嘗試創建一個可以選擇下一個選項的按鈕。使用jQuery選擇下一個選項

所以,我有一個選擇(ID = selectionChamp)有幾個選項,輸入下一個(ID = fieldNext),我嘗試這樣做:

$('#fieldNext').click(function() { 
    $('#selectionChamp option:selected', 'select').removeAttr('selected') 
      .next('option').attr('selected', 'selected'); 

    alert($('#selectionChamp option:selected').val());  
}); 

但我不能選擇下一個選項.. 謝謝 !

+0

您是否正在加載頁面加載DOM? – Dev 2012-07-19 08:14:20

+0

你是什麼意思? – 2012-07-19 08:15:36

+0

意味着你在準備就緒的功能中使用該代碼嗎? – Dev 2012-07-19 08:24:51

回答

22
$('#fieldNext').click(function() { 
    $('#selectionChamp option:selected').next().attr('selected', 'selected'); 

    alert($('#selectionChamp').val());  
}); 
+1

FF中損壞32.0.3 – njahnke 2014-10-09 00:58:28

+4

需要同時取消選擇當前選項,例如'$('#selectionChamp option:selected')。attr('selected',false);' – anthonygore 2015-02-10 01:10:32

+0

是的......但是隻有在選擇標籤上設置了多個屬性。但是,如果你想要更新答案以.... – bugwheels94 2015-02-10 18:56:47

0
$('#fieldNext').click(function() { 
$('#selectionChamp option:selected').removeAttr('selected') 
     .next('option').attr('selected', 'selected'); 

alert($('#selectionChamp option:selected').val());  
}); 
12
$("#fieldNext").click(function() { 
    $("#selectionChamp > option:selected") 
     .prop("selected", false) 
     .next() 
     .prop("selected", true); 
});​ 

DEMO:http://jsfiddle.net/w9kcd/1/

0

試試這個:

$(document).ready(function(){ 
     $("#fieldNext").on("click",function(){ 
      $optionSelected = $("#selectionChamp > option:selected"); 
      $optionSelected.removeAttr("selected"); 
      $optionSelected.next("option").attr("selected","selected");  
     }); 
    }); 
2
$(function(){ 
    $('#button').on('click', function(){ 
    var selected_element = $('#selectionChamp option:selected'); 
    selected_element.removeAttr('selected'); 
    selected_element.next().attr('selected', 'selected'); 

    $('#selectionChamp').val(selected_element.next().val()); 

    }); 
}); 

http://jsbin.com/ejunoz/2/edit

8

沒有jQuery也很簡單。這人會圍繞循環一次最後的第一個選項達到:

function nextOpt() { 
    var sel = document.getElementById('selectionChamp'); 
    var i = sel.selectedIndex; 
    sel.options[++i%sel.options.length].selected = true; 
} 

window.onload = function() { 
    document.getElementById('fieldNext').onclick = nextOpt; 
} 

一些測試標記:

<button id="fieldNext">Select next</button> 
<select id="selectionChamp"> 
<option>0 
<option>1 
<option>2 
</select> 
+0

+1。你已經發布了一些好的香草JS解決方案!幫助很多! – A1rPun 2013-12-05 13:59:06

0

的其他解決方案不工作的情況下也有選項組元素除了選項元素。在這種情況下,這似乎工作:

var options = $("#selectionChamp option"); 
var i = options.index(options.filter(":selected")); 
if (i >= 0 && i < options.length - 1) { 
    options.eq(i+1).prop("selected", true); 
} 

(你可能會認爲,對於i表達也可以寫成options.index(":selected"),但是,這並不總是工作,我不知道爲什麼,說明會。 )