1

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...

1
  • Not sure why you postID wouldn't be accessible from your JS file, but I think your original method is the better one. Commented May 25, 2011 at 16:09

2 Answers 2

2

to get the val of postId use

alert($("input#postId").val());
Sign up to request clarification or add additional context in comments.

4 Comments

the postId is not accessible from my JS file :/
if you are putting multiple inputs on your page, you must be aware that ID has to be unique, so i recommend setting class variable, so class='input1' id='postId', class='input2' id='postId', or you could do class='input' id='1', class='input' id='2'
Can't I directly reference the input without using a class or an Id?
$("input").someFunction() will refference all inputs, if you have a input with a class name and a id name you reference it like this: $("input.className#idName");
2

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"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.