Reputation: 31
My problem is that the else section here doesn't seem to work. I already surfed the web for a solution and even though there are very many questions exactly like mine, the answer always seems to be different.
This is the button I click on
<input type="submit" value="4">
I also have a button like this:
<input type="submit" id="b1" value="Back">
My Aim is to find out if the button with an ID was clicked or not.
var specify = "";
var prevpos = 0;
$('input[type=submit]').click(function(){
specify = $(this).attr('value');
if($(this).attr('id').substring(0,1) == "b")
{
$("html, body").animate({scrollTop: prevpos}, 777);
$(".right").animate({opacity: 0.0}, 200);
$(".left").animate({opacity: 1.0}, 200);
// more stuff here
}
else
{
$("html, body").animate({scrollTop: prevpos}, 777);
// more stuff here
}
});
As always, any help is greatly appreciated!
Upvotes: 0
Views: 169
Reputation: 2491
I had a similar requirement some time ago and here's my solution:
var specify = "";
var prevpos = 0;
$('input[type=submit]').click(function(e){ //Note the addition of 'e'
var id = e.target.id; // If the element has no ID you should get an empty string here
specify = $(this).attr('value');
if( id.match(/^b/) ) { // This is a regular expression, if the ID starts with 'b' then it matches
$("html, body").animate({scrollTop: prevpos}, 777);
$(".right").animate({opacity: 0.0}, 200);
$(".left").animate({opacity: 1.0}, 200);
// more stuff here
} else {
$("html, body").animate({scrollTop: prevpos}, 777);
// more stuff here
}
});
Upvotes: 0
Reputation: 337590
The problem with your code is because when you click the button without an id
you are calling substr()
on a null, which will cause errors.
Try this instead:
var specify = "";
$('button').click(function () {
specify = $(this).attr('value');
var id = $(this).attr('id');
// check there is an id, and if so see if it begins with 'b'
if (id && id.substring(0, 1) == "b") {
alert("You clicked the button WITH an id");
}
else {
alert("You clicked the button WITHOUT an id");
}
});
Upvotes: 4
Reputation: 6730
var specify = "";
var prevpos = 0;
$('input[type=submit]').click(function(){
specify = $(this).attr('value');
if($(this).attr('id') && $(this).attr('id').substring(0,1) == "b")
{
$("html, body").animate({scrollTop: prevpos}, 777);
$(".right").animate({opacity: 0.0}, 200);
$(".left").animate({opacity: 1.0}, 200);
// more stuff here
}
else
{
$("html, body").animate({scrollTop: prevpos}, 777);
// more stuff here
}
});
You probably need to check whether the element has the id attribute at all before checking on its value.
Upvotes: 2