2

Please advice, how to find selected value of a html select on its change.

code is below

$(".js-CellFirst").change(function () {
            alert($(this.find('option:selected')).text());<-- **trouble line**
});

thanks

jhanifen
  • 4,441
  • 7
  • 43
  • 67
Amit
  • 6,839
  • 21
  • 56
  • 90
  • 2
    possible duplicate of [To get selected value of a dropdown ( – alex Apr 20 '11 at 04:00

2 Answers2

3

To get the value...

$(".js-CellFirst").val();

To get the text of the selected option element.

$(".js-CellFirst option:selected").text();

However, your specific issue is with your parenthesis, of which you have nested correctly. The correct use is...

alert($(this).find('option:selected').text());
alex
  • 479,566
  • 201
  • 878
  • 984
  • The jQuery library provides .val() for a reason: text() and others have some browser inconsistency. The val method works for nearly any object in jQuery. – Levi Morrison Apr 20 '11 at 04:04
  • @Levi Browser inconsistency is a strong reason why jQuery exists. I don't understand what your comment is getting at... – alex Apr 20 '11 at 04:07
  • @alex Don't use .text(), use .val(). Text only works on certain types of elements, but val works on nearly all. That's all I'm saying. – Levi Morrison Apr 20 '11 at 04:31
  • @Levi To get an element's text node? – alex Apr 20 '11 at 04:32
  • @alex http://stackoverflow.com/questions/807867/what-is-the-difference-between-jquerys-functions-val-and-text – Levi Morrison Apr 20 '11 at 04:35
  • @alex, I'm not the best at explaining things sometimes. That question sums it nicely. – Levi Morrison Apr 20 '11 at 04:37
  • @Levi I am using `text()` to get the text node of an `option` element, which should use `innerText` or `textContent` internally, and I have never had an issue with it. – alex Apr 20 '11 at 04:37
  • @alex all I know is that the jQuery docs says 'The .text() method cannot be used on input elements. For input field text, use the .val() method.' It seems to also be the case for other form elements, though I can't find it said anywhere. – Levi Morrison Apr 20 '11 at 04:44
  • @Levi I'm not using it *on* an input element, per se, more a child element of an input. – alex Apr 20 '11 at 04:45
2

Get selected value of a dropdown's item using jQuery

Just use alert($(this).val(); instead:

$(".js-CellFirst").change(function () {
        alert($(this).val());
});
Community
  • 1
  • 1
no.good.at.coding
  • 20,221
  • 2
  • 60
  • 51