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:

http://jsbin.com/weput/1/

<!doctype html> <html> <head>   <meta charset="utf-8">   <title>js bin</title> </head> <body> <button onclick="setoption(-1)">&#8592;</button> <button onclick="setoption(1)">&#8594;</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!

demo

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">&#8592;</button> <button id="nextoption">&#8594;</button> 

and need:

live demo 2

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:

live demo 3

$('#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

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -