I have a <select> element on my form with the multiple attribute set to "true". After the element gets populated, how can I select the last item in the list using jquery? I want the item to be selected the same way you select it with a mouseclick:
Asked
Active
Viewed 8,858 times
5
broke
- 7,802
- 14
- 53
- 82
-
@Nivas: Your first duplicate link seems right, but definitely not the second one. You should have just voted to close with your first link. – BoltClock May 07 '14 at 15:52
-
@BoltClock Agreed - the second one is not related. I did not intend to post that. Need more coffee. (I already did flag to close and now deleted the second comment) – Nivas May 07 '14 at 15:55
-
I don't really understand what you need, but here my fiddle http://jsfiddle.net/keypaul/kfLf7/1/ – keypaul May 07 '14 at 16:09
2 Answers
5
You can try
var myVal = $('.someclass option:last').val();
$('.someclass').val(myVal);
where someclass is the select class or it's wrapper element class.
alou
- 1,362
- 12
- 16
5
You can do this by index value as well:
var num = $('select option').length;
$('select').prop('selectedIndex', num-1); // For choosing last item in list
gtr1971
- 2,572
- 2
- 16
- 23
-
2This answer was better for me in my case because of duplicate values (fringe case) – Rick Kukiela Jan 17 '18 at 16:35