jquery - Select List Manipulation -
this question similar @ least 1 other question, resolution didn't me. have code worked great in jquery 1.4, works no longer. have 2 buttons (used to) allow user navigate thru select list. here's working version:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>js bin</title> </head> <body> <button onclick="setoption(-1)">←</button> <button onclick="setoption(1)">→</button> <select name="select1" id="select1"> <option value=""></option> <option value="one">one</option> <option value="two">two</option> <option value="three">three</option> </select> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> </body> </html>
js:
function setoption(num) { var current = $( "#select1" ).attr( "selectedindex" ) var next = current + num; $('#select1 option:eq('+next+')').attr('selected', 'selected'); }
what need update make work in, say, jquery 1.11.0?
thanks in advance!
use .prop()
function setoption(num) { var current = $( "#select1" ).prop( "selectedindex" ); var next = current + num; $('#select1 option:eq('+next+')').prop('selected', true); }
try avoid using inline js cause hardly maintainable.
use rather id selectors like:
<button id="prevoption">←</button> <button id="nextoption">→</button>
and need:
function setoption() { var num = this.id.match('prev') ? -1 : 1; var curr = $("#select1").prop("selectedindex") + num; $('#select1 option:eq('+curr+')').prop('selected', true); } $('#prevoption, #nextoption').click( setoption );
or code:
$('#prevoption, #nextoption').click(function(){ var n = this.id.match('prev')?-1:1; $('#select1').prop("selectedindex", function(i,v){return v+n;}); });
some readings:
.prop() vs .attr()
https://softwareengineering.stackexchange.com/questions/86589/why-should-i-avoid-inline-scripting
when should use inline vs. external javascript?
Comments
Post a Comment