JQuery: How to determine which <li> tag was clicked?
I create a form with 5 lines of text, and each text I let the user choose whether they want the text to be centered, left or right. I have an unordered list with x5 list items.
<li><img src="images/justify_left.png" alt="left" /><span>Justify Left</span></li> <li><img src="images/justify_center.png" alt="center" /><span>Justify Left</span></li> <li><img src="images/justify_right.png" alt="right" /><span>Justify Left</span></li> Each of the 5 sets of <li> elements belongs to the corresponding line.
With jQuery, how would I decide to determine which of the 15 <li> elements the user selected so that I can fit the correct rationale as the post method?
In the callback handler, this refers to the <li> click. You may want to add a class only for these list items or place them in a div with such a class, this will allow you to target them and put an event in them. Also, note that alt is not valid here, you are probably looking for title .
$('li').click(function(){ var justify = $(this).attr('alt'); alert(justify); }); You might want to set a hidden field for this. You can do this, for example, by adding $('#hiddenJustify').val(justify) .
Since you have five groups of these <li> s, you probably want to group them under one element. For example:
<div class="line-justify-group"> <ul> <li>...</li> <li>...</li> <li>...</li> </ul> <input type="hidden" name="line1justify" id="line1justify" class="justify-value" /> </div> Then you can install it using the code:
$(this).closest(".line-justify-group").find(".justify-value").val(justify); Then the items will be sent to the server.
<!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#list1 li').bind("click", function(e) { e = e || window.event; var ul = $(this).parent(); var index = ul.children().index(this); alert(index); }); }); </script> </head> <body> <ul id="list1"> <li><img src="images/justify_left.png" alt="left" /><span>Justify Left</span></li> <li><img src="images/justify_center.png" alt="center" /><span>Justify Left</span></li> <li><img src="images/justify_right.png" alt="right" /><span>Justify Left</span></li> </ul> </body> </html> for each tag, li or img or span assigns it a unique id attribute. The same meaning as the alt text in your example will be good enough.
Assuming you have an onclick event, you can pass jquery to this object functions, and then get the alt attribute.
onclick="getJustification($(this));" Then in getJustification:
getJustification(selectedObj) { if(selectedObj.attr('id') == 'left') ... // for each unique id } NB: the code is written without a link, from the top of the head. I hope he can push you in the right direction.