Die 20
Die 20

Reputation: 261

Grabbing a value from an input field with jQuery

I am trying to grab a value from an input field within jquery but I keep getting an undefined variable. The content is loaded dynamically so I need to use (this) and classes.

here is the html:

<div class="menu_page_container">
    <div class="page_link">NAME</div>
    <input type="hidden" value="5" class="page_id" />       
</div>

jQuery:

$(document).ready(function () {
    $(".page_link").on('click', function () {
        var item_id = $(this).find(".page_id").attr("value");
        alert(item_id);
    });
});

Upvotes: 1

Views: 100

Answers (1)

SomeShinyObject
SomeShinyObject

Reputation: 7821

Use siblings(). siblings() gets the siblings of a node by a given selector.

$(document).ready(function () {
    $(".page_link").on('click', function () {
        var item_id = $(this).siblings(".page_id").val();
        alert(item_id);
    });
});

jsFiddle

Upvotes: 2

Related Questions