Reputation: 3270
I currently have a button that when clicked it passed that buttons id to a function and the function alerts this id name. Now the alert displays the right name but when I click okay on the alert it takes me back to the homepage. Here is the code:
JS:
function ButtonPicture(id)
{
alert(id);
}
HTML:
<input type="submit" onclick="ButtonPicture(this.id);" id="car1" value="Take Picture">
I'm not sure why this is happening and how to prevent this
Upvotes: 1
Views: 61
Reputation: 17023
You have attached your function to a submit input element. By default, when you click a submit button, the browser will submit a form attached to it, which, will redirect the page to the action specified of the form. If no action is specified, it will redirect to the current page.
You need to prevent the default action here. You have many options, but I present two common options below:
JQuery
$(document).ready(function() {
$("#car1").click(function(e) {
e.preventDefault();
ButtonPicture(this.id);
});
});
Notice: You don't need to wrap this in $(document).ready(function() { });
if you place this code after your input element in the document.
HTML
<input type="submit" id="car1" value="Take Picture">
You can return false from the onclick
event:
<input type="submit" onclick="ButtonPicture(this.id); return false;" id="car1" value="Take Picture">
My personal preference and recommendation would be option 1
Upvotes: 2