views:

23

answers:

1

I have a dynamic list of items that will be used to POST information to the backend using AJAX.

<a href="...">Item 1</a>
<a href="...">Item 2</a>
<a href="...">.....</a>
<a href="...">Item n</a>

I've decided to include a css class and a hidden input on each item so that I can easily assign the handler (using the css class) and so that I can know the ID of the item (using the hidden field).

<a href="..." class="recorditem"><input type="hidden" value="1" name="ItemID"/>Item 1</a>
<a href="..." class="recorditem"><input type="hidden" value="2" name="ItemID"/>Item 2</a>
...
<a href="..." class="recorditem"><input type="hidden" value="n" name="ItemID"/>Item n</a>

Then with jQuery, I will intercept the click on the link (which would go to a page for non-javascript users) to do a POST. So it will look something like this:

 $("a.recorditem").click(function(){
        //get the item ID
     var itemID = $(this + " :input[name='ItemID']").val(); <-- PROBLEM

        //build a form dynamically - omitted for readability
        var formToAdd = "<input type='text'.... "
        //etc etc...
    });

Except, I cannot for the life of me figure out how to extract the value of the hidden input field from the link within.

What am I doing incorrectly? Better yet, is this even a smart way to do this for a dynamic list?

+2  A: 

Not sure if a hidden input is valid in an anchor (W3c)...never tried it.

Does the follwoing work

var itemID = $(this).children().eq(0).val();
redsquare
It works. I too am not sure if it's valid within an anchor. (I'm just writing some crude tests in notepad). Is there a better way to handle this situation, as in, where can I place the ID of the item I need?
MunkiPhD
you can use a html5 data- attribute on the anchor itself
redsquare
see http://ejohn.org/blog/html-5-data-attributes/ for more info
redsquare