Mohamad
Mohamad

Reputation: 35359

How do I reference the value of an input in jQuery?

I'm currently using the following method to return a value from a div:

<div data-post-id="1">
   <a>Add To Favourites</a>
<div>

$(this).parent().data('post-id');

What I would like to do is something like this:

<div>
   <input type="hidden" name="postId" value="1" />
   <a>Add To Favourites</a>
<div>

Keep in mind:

  1. There will be several posts on each page. Each div containing a post will have it's own input.

  2. The value of the postId will not be accessible from my JS file. So the its reference has to be retrieved via JavaScript somehow.

I want to get away from using parent() and use a single reference for each post's id, regardless whether the action is to favourite, send to a friend, etc...

Upvotes: 1

Views: 71

Answers (2)

patorjk
patorjk

Reputation: 2182

You could use an attribute selector to get the hidden inputs. Just add a "isPostId" field to your hidden input and then grab them with the jQuery object:

$('div input[isPostId="true"]')

<input type="hidden" isPostId="true" value="1"/>

Upvotes: 2

John
John

Reputation: 1319

to get the val of postId use

alert($("input#postId").val());

Upvotes: 2

Related Questions