Eugene
Eugene

Reputation: 15

How to add class on click with jQuery to list item?

I have a list item like

<ul>
    <li><img id="1" src="" /></li>
    <li><img id="2" src="" /></li>
    <li><img id="3" src="" /></li>
</ul>

<input type="button" >

I would like on click of any of the list to add class and remove from others with jQuery. Basically to make only one item selected at the time.

and on button click to show id of selected list item

Upvotes: 1

Views: 24161

Answers (4)

Muhammad Usman
Muhammad Usman

Reputation: 12503

See it working here http://jsfiddle.net/usmanhalalit/Jbh3q/1/

I have slightly changed your markup to match with the standard(just added id) and added a red background with to show the effect in the fiddle.

Markup:

<ul id="myul">
    <li><img id="1" src="" /></li>
    <li><img id="2" src="" /></li>
    <li><img id="3" src="" /></li>
</ul>

<input id="btn" type="button" value="click" />

JavaScript:

$(function(){

    $("#myul li").click(function(){
        $("#myul li").removeClass('selected');    
        $("#myul li").css('background','none');    
        $(this).css('background','red');   
        $(this).addClass('selected');    
    });

  $('#btn').click(function(){
    alert( $('.selected img').attr('id') );
  });

});

Upvotes: 1

John Hartsock
John Hartsock

Reputation: 86862

This will do what you want AND get you the ID of the img tag within the selected li

$('ul > li').click(function() { 
  $('ul > li').removeClass('active'); 
  $(this).addClass('active'); 
});

$('input:button').click(function() {
  alert($('li.active img')).attr('id')); 
});

Upvotes: 6

PeeHaa
PeeHaa

Reputation: 72652

$('li').click(function() { // should be better selector than just li
  $('li').removeClass('active'); // remove all active classes
  $(this).addClass('active'); // add active class to element clicked
});

$('input[type="button"]').click(function() {
  alert($('li.active img').attr('id')); // get active id
});

EDIT misread your code. Added the fix to get the id of the image tag.

Upvotes: 1

Morgan Delaney
Morgan Delaney

Reputation: 2439

// On li click
$("li").click(function() {
  // Reset them
  $("li").removeClass("yourClass");
  // Add to the clicked one only
  $(this).addClass("yourClass");
});

// On button click
$("input[type=\"button\"]").click(function() {
  // Echo the id of selected li
  alert($(".yourClass").attr("id"));
});

Upvotes: 0

Related Questions