As according to the advice at Prevent form redirect OR refresh on submit? , I have my form which is
<form id="editingForm">
Line height (between 10 and 60):
<input type="number" id="LineHeightEntry" name="LineHeightEntry" min="10" max="60" value="30">
<input type="submit" id="submitLineChange" value="Submit">
</form>
In a file called test.html. The javascript is
$('#editingForm').submit(function(){
alert("abc");
return false;
});
The intent is to have the function be called, and then javascript can do something to the page, but the page is not reloaded or redirected elsewhere. However, instead what I get is say I set LineHeightEntry to 40 and hit submit. Then it redirects to test.html?LineHeightEntry=40. Why does it do that?
edit - The file is at http://probuling.net/sandbox/test.html
4 Answers 4
Here is a working example:
<html>
<head>
<script src="jquery-1.9.1.min.js"></script>
</head>
<form id="editingForm" action="toto">
Line height (between 10 and 60):
<input type="number" id="LineHeightEntry" name="LineHeightEntry" min="10" max="60" value="30">
<input type="submit" id="submitLineChange" value="Submit">
</form>
<script>
$('#editingForm').submit(function(event)
{
alert("abc");
event.preventDefault(); // if you want to disable the action
return false;
});
</script>
</html>
6 Comments
Add action attribute to the form or you are just refreshing the page on submit.
<form id="editingForm" action="/another/url">
I would recommend learning how to use normal form submit before even try using Javascript. Any input with name attribute will be appended to the URL since you have no action and default method is set to GET.
3 Comments
remove line return false;
This prevent default event. Read more detail: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/
Comments
try doing it without jQuery. Also, try using the event.preventDefault
document.querySelector('#editingForm').onsubmit = function(event) {
alert('abc');
event.preventDefault();
return false;
};
actionattribute in yourform...as I dont see it