2012-07-19 6 views
19

次のオプションを選択できるボタンを作成しようとしています。jQueryで次のオプションを選択

だから、私はいくつかのオプション、入力次(ID = fieldNext)を選択(ID = selectionChamp)を持っている、と私はそれをやろう:

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

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

しかし、私は、次のオプションを選択することはできません..ありがとう!

+0

ページロード時にDOMをロードしていますか? – Dev

+0

どういう意味ですか? –

+0

は、そのコードを準備機能で使用していますか? – Dev

答えて

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

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

FFで壊れた32.0.3 – njahnke

+4

また、現在のオプションの選択を解除する必要があります。 '$('#selectionChamp option:selected ')。attr(' selected '、false); ' – anthonygore

+0

ええと...ただし、selectタグに複数の属性が設定されている場合に限ります。しかし、必要ならば自由に回答を更新することができます〜に.... – bugwheels94

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もありません。最後に、一度最初のオプションの周りのこの1人の意志ループが到達した:

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ソリューションを投稿しました! alotを助ける! – A1rPun

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")のように書くことができることを考えるかもしれないが、それは常に動作しません。私は、なぜ説明を知らないでしょう。歓迎してください。)

関連する問題