views:

54

answers:

2

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

+3  A: 

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.

Felix Kling
$('select option:last').val() its not working...answer given by pointy is working..var lastValue = $('#idOfSelect option:last-child').val();Can u figure out why ur code is not working...In case of ur code i m getting undefined..
piemesons
@piemesons: Don't know, works for me... But I realize that `:last-child` might be indeed better.
Felix Kling
+4  A: 

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;
Pointy
+1 for referencing the Javascript "under the covers"
Robusto