I need to know how to get id of the last selected item in a multiple list box using javascript. It keeps on givin me 0 or 1...any tips would be great. Note i wanna store it in a variable and that variable should store id of the last selected item.
selectedIndex value of the last selected item in select box
Collapse
X
-
I haven't done much with forms in JavaScript but I'd imagine you could do this with something like
Code:var x = selected.item( selected.length - 1 ).id
-
Comment
-
Now i wanted to store id of the last clicked item in lastindex variable.Code:function SelectedItems(selectBoxName,maxallowed) { //used to know how many items selected in <select box> var obj=document.getElementById(selectBoxName); var lastclicked=obj.selectedIndex; var btnobj=document.getElementById(submitbutton);//submit or upload or so button. var numberSelected=0 for (var i=0; i < obj.options.length; i++) { if (obj.options[i].selected == true){ numberSelected++; }//end if }//end loop if (numberSelected>maxallowed){ alert("You can't select " + maxallowed + " items. Please deselect at least one item to proceed."); btnobj.disabled=true; obj.options[lastIndex].selected=false; return; }//end if else{ }//end else }//end functionComment
-
Hi samvb,
I was not able to understand you requirement clearly. I just gone through your code. From that I can understand that you are having a multiple select element. You can select so many options. Whether you want to find which option was selected finally?
Thanks and Regards
Ramanan KalirajanComment
-
I misunderstood your post.
Also do note we must use the onmousedown function not onclick or onmouseup onchange will happen before onclick and onmouseup in term making the function deslected the wrong option.Code:<script type="text/javascript"> var lastIndex = false; function validate( select ) { var max = 3; var x; var count = 0; for( x = 0; x < select.options.length; x++ ) { if( select.options[x].selected == true ) count++; } if( count > max ) { alert( "To many items selected!" ); select.options[lastIndex].selected = false; } } </script> <select id="myselect" onchange="validate( this );" multiple="multiple"> <option onmousedown="lastIndex = this.index">1</option> <option onmousedown="lastIndex = this.index">2</option> <option onmousedown="lastIndex = this.index">3</option> <option onmousedown="lastIndex = this.index">4</option> <option onmousedown="lastIndex = this.index">5</option> <option onmousedown="lastIndex = this.index">6</option> <option onmousedown="lastIndex = this.index">7</option> </select>Comment
Comment