I have an issue while using buttons inside form. I want that button to call function. It does, but with unwanted result that it refresh the page.
My simple code goes
For any reason in Firefox even though I have return false;
and myform.preventDefault();
in the function, it refreshes the page after function runs. And I don't know if this is a good practice, but it works for me, I insert javascript:this.preventDefault();
in the action attribute .
As I said, I tried all the other suggestions and they work fine in all browsers but Firefox, if you have the same issue, try adding the prevent event in the action attribute either javascript:return false;
or javascript:this.preventDefault();
. Do not try with javascript:void(0);
which will break your code. Don't ask me why :-).
I don't think this is an elegant way to do it, but in my case I had no other choice.
Update:
If you received an error... after ajax is processed, then remove the attribute action and in the onsubmit
attribute, execute your function followed by the false return:
onsubmit="functionToRun(); return false;"
I don't know why all this trouble with Firefox, but hope this works.
This one is the best solution:
<form method="post">
<button type="button" name="data" onclick="getData()">Click Me</button>
</form>
Note: My code is very simple.
The problem is that it triggers the form submission. If you make the getData
function return false
then it should stop the form from submitting.
Alternatively, you could also use the preventDefault method of the event object:
function getData(e) {
e.preventDefault();
}
Let getData()
return false. This will fix it.
<form method="POST">
<button name="data" onclick="return getData()">Click</button>
</form>
<form onsubmit="return false;" id="myForm">
</form>
$('#myForm').submit(function() {
doSomething();
});
I was facing the same problem. The problem is with the onclick
function. There should not be any problem with the function getData
. It worked by making the onclick
function return false.
<form method="POST">
<button name="data" onclick="getData(); return false">Click</button>
</form>