Why does val() returns undefined?-Collection of common programming errors
i try to get the value of the next hidden input field when a button is clicked but my script always returns “undefined”. What am i doing wrong and why does val() returns undefined? If only try to select the element with next(‘input:hidden’) the function returns an object.
Er will dich 1
Er will dich nicht 5
Es ist alles offen 2
Er will dich 1
Er will dich nicht 5
Es ist alles offen 2
JavaScript:
$(document).ready(function() {
$('button.rating-button').click(function(event) {
event.preventDefault();
var $rating = $(this).attr('value');
var $messageId = $(this).next('input:hidden').val();
alert('test'+$messageId);
});
});
-
It happens because there is no
next
element for . You have to go up the DOM tree until and find the hidden element:var $messageId = $(this).closest(".message-ratebox").find("input:hidden").val();
or to go up until
- and select the
next
element:var $messageId = $(this).closest("ul").next("input:hidden").val();
-
$('button.rating-button').click(function(event) { event.preventDefault(); var $rating = $(this).val(); var $messageId = $(this).parent().parent().parent().find('input').val(); alert($rating + $messageId ); });
-
You need to parse back up from the button to the input’s container, which in this case is the nearest div, and then parse back down to the hidden input…
$('button.rating-button').click(function(event) { event.preventDefault(); var $rating = $(this).val(); var $messageId = $(this).closest("div").find('input[type=hidden]').val(); alert($rating + $messageId); });
Originally posted 2013-11-09 19:41:39.