2012-07-19 2 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

+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 옵션 : selected'). attr ('selected', false); ' – anthonygore

+0

예 ... 선택 태그에 여러 속성이 설정된 경우에만 가능합니다. 그러나 원할 경우 자유롭게 대답을 업데이트 할 수 있습니다. ~ .... – 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가 없어도 간단합니다. 지난 번 첫 번째 옵션에 주변이 하나의 의지 루프에 도달 :

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

0

다른 솔루션을 옵션에 추가 요소 optiongroup가있는 경우에는 작동하지 않습니다 집단. 이 경우,이 작동하는 것 같다 :

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")로 작성 될 수 있다고 생각할 수 있지만, 항상 내가, 설명이 왜 모르는 작동하지 않습니다. 환영합니다.)