I have simple HTML code:
<input type='hidden' name='cat_id' value='123'/>
<a href='#' class='edit'>Edit</a>
<a href='#' class='delete delete-link'>Delete</a>
And simple JS code:
$("a.delete-link").click(function() {
var id = $(this).prev($('input[name="cat_id"]')).val();
alert(id);
});
Everything simple and obvious, get a value of previous input with name ‘cat_id’. But it just returns an empty string (value is really defined). I thought maybe selector is wrong:
var id = $(this).prev($('input[name="cat_id"]')).length;
alert(id);
Returns 1. Working.
I just didn’t have a clue what’ happening and tried
var id = $(this).prev($('input[name="cat_id"]')).attr('name');
alert(id);
Returns ‘undefined’. Strange. Any ideas? Tried prevAll instead of prev, effect is the same. jQuery version is 1.6.4
The
prevmethod takes a selector, not a jQuery object:However, just that won’t help you in this case. As the selector doesn’t match the previous element (the edit link), you will get an empty jQuery object, and
valwon’t return the id.You can use the
siblingsorprevAllmethod to find the element: