开发者

Get value of last option of a drop down?

开发者 https://www.devze.com 2022-12-23 14:30 出处:网络
I have dropdown menu..which is dynamic.. How can get value of the last item in that开发者_开发技巧 drop down (using jquery is also acceptable)With jQuery it\'s super easy:

I have dropdown menu..which is dynamic.. How can get value of the last item in that开发者_开发技巧 drop down (using jquery is also acceptable)


With jQuery it's super easy:

var lastValue = $('#idOfSelect option:last-child').val();

With plain Javascript it's not much worse:

var theSelect = document.getElementById('idOfSelect');
var lastValue = theSelect.options[theSelect.options.length - 1].value;


With jQuery:

$('select option:last').val()

Of course you should use a proper ID to address the select element.

If you mean "menu" it terms of a list, you can do it similar:

// gives the text inside the last <li> element
$('#menu li:last').text()

// gives you the attribute 'some_attribute' of the last <li> element
$('#menu li:last').attr('some_attribute')

The key here is to use the :last selector.


One more way of doing this

   $('select option').last().val()

or for list

   $('ul li').last().text()

While above 2 suggestions are perfectly valid, I feel this approach is cleaner than modifying the selector.

Offcourse you should add id/class of specific select/ul if you want to target the particular menu/list.


Using attributte selected.

$('#SelectName option:last-child').attr('selected', 'selected');


$('#id_of_select option:last-of-type').click();

OR

$('#id_of_select option:last-child').click();

Both of these should find and click on the last option on any dynamic drop-down list.

0

精彩评论

暂无评论...
验证码 换一张
取 消