Reputation: 33755
So I have captured the ID of an image in a jquery variable like so:
$("#tag img").click(function(e) {
var element = $(this).attr("id");
How do I then parse the var element?
I would like to put it in an if statement like this:
if ( $(element *= 'square' ) {
$('#tag #view_name').text("Tag with a Square");
}
elseif ($(element *= 'circle' ) {
$('#tag #view_name').text("Tag with a Circle");
}
How do I do that, with the least amount of code possible?
Thanks.
Edit: Oh, and the text I am searching for are the two strings in the single quotes ('square' and 'circle').
Edit: All of the answers below look like they should be working...but they aren't. Here is the other code, so you guys can see if I am missing something:
<div id="tag">
<a href=""><img src="images/square.png" id="square-tag"></a> |
<a href=""><img src="images/circle.png" id="circle-tag"></a> |
<span id="view_name">Tag with Square</span>
</div>
Edit 3: Ok...it seems that some other jQuery was hijacking that div. All the answers are right. I wish I could mark all of them correct :)
Upvotes: 1
Views: 172
Reputation: 630409
From a minimal code standpoint, this would work:
$("#tag img").click(function() {
if (this.id.indexOf('square')>-1) {
$('#view_name').text("Tag with a Square");
} else if (this.id.indexOf('circle')>-1) {
$('#view_name').text("Tag with a Circle");
}
});
When selecting by ID use only the ID, it's a faster selector as well. I'm doing it this way because of how your question's phrased, for this specific example, it's a bit cleaner to do:
$("#tag img[id*='square']").click(function() {
$('#view_name').text("Tag with a Square");
});
$("#tag img[id*='circle']").click(function() {
$('#view_name').text("Tag with a Circle");
});
Upvotes: 3
Reputation: 29658
Try this:
if (element.indexOf("square") != -1)
$('#tag #view_name').text("Tag with a Square");
else if (element.indexOf("circle") != -1)
$('#tag #view_name').text("Tag with a Circle");
Upvotes: 1
Reputation: 68006
This is similar to $("input[name*='man']")
selector (example from your comment)
var name = $(this).attr("name");
if (name.indexOf('square') >= 0) {
$('#tag #view_name').text("Tag with a Square");
}
Upvotes: 2