Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to determine which <li> tag was clicked?

Tags:

jquery

I am creating a form with 5 lines of text, and each text I am allowing the user to select if they want the text to be centered, left, or right justified. I have a unnumbered list with list elements x5.

<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 set of <li> items refers to its respective line.

With jQuery, how would I go about determining which of the 15 <li> items did the user select so that I can correspond the proper justification as a post method?

like image 719
Magnum Avatar asked May 11 '10 05:05

Magnum


People also ask

How do I know which anchor is clicked in jQuery?

you just need to do this : $(document). ready(function () { $('#document_dropdown . notify').

How can you tell which element has been clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.

How do I know if my span is clicked?

The colors' span/block should be clicked. When one of them is clicked , the icon should be displayed. When another one of the colors is clicked, icon should be displayed but the previous icon that was displayed should now be hidded.

What is Click () method?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.


1 Answers

On the click handler's callback, this refers to the clicked <li>. You may want to add a class just for these list items, or place them in a div with such class, this will allow you to target them and bing the event to them. Also, note that alt is invalid here, you're probably looking for title.

$('li').click(function(){
   var justify = $(this).attr('alt');
   alert(justify);
});

You may want to set an hidden field to that value. You can do that, 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>

You can then set it using the code:

$(this).closest(".line-justify-group").find(".justify-value").val(justify);

The items will then be posted to the server.

like image 141
Kobi Avatar answered Sep 18 '22 01:09

Kobi