Ramin
Ramin

Reputation: 391

How can I get the ID of a picture that user click on it?

I would try to have something like five star rating , but not alone , I would like it a part of a form that user have to click on it and also enter his opinion about article , how can I retrieve the ID of picture (1start,2stars,...) that clicked on after submiting form? Also I would like to have validation on it , I mean user have to click on five star picture. I would like to use jquery

Upvotes: 2

Views: 187

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 174957

$('img').click(function() { alert($(this).attr('id')); });

Should do the trick for you. .attr() returns an attribute from an element.

EDIT: As per OP request:

HTML:

<input type="image" value="1" name="vote" src="star.gif" />
<input type="image" value="2" name="vote" src="star.gif" />
<input type="image" value="3" name="vote" src="star.gif" />
<input type="image" value="4" name="vote" src="star.gif" />
<input type="image" value="5" name="vote" src="star.gif" />

jQuery:

$('input[type="image"][name="vote"]').click(function() { alert($(this).val()); return false; });

This will alert the input's value, note that <input type=image> is a more semantic way to describe functional images, and should be used instead of <img> tags.

Also note that you could store the vote in a variable just as easy by using

storedVote = $(this).val(); //Of course goes within the click handler.

WORKING EXAMPLE

Upvotes: 3

James Sumners
James Sumners

Reputation: 14777

Given the following element:

<img id="starImage1" class="starImage" src="star1.png">

You can do the following with jQuery:

$('.starImage').bind('click', function() {
    alert(this.id);
});

This binds a function to all elements with the "starImage" class that alerts the clicked element's ID attribute.

Upvotes: 1

Related Questions