I have a form with just one field:
<form id="formCode" onsubmit="return saveCode()" />
<label for="fcode">Type Code:</label><br>
<input type="text" id="fcode" name="fcode" autofocus /><br>
<input type="submit" value="Submit – Enviar" onclick="return saveCode()" />
</form>
This is the Javascript I have on the page:
document.addEventListener("keydown", function(inEvent){
if (inEvent.keyCode == 13) { // enter
if (document.getElementById("fcode").value === "") { return; } // do nothing
saveCodeCode();
return false;
}
});
function saveCode() {
var codeField = document.getElementById("fcode");
var value = codeField.value;
if (value === "") { return false; }
saveValue(value);
codeField.value = "Submitted";
return false;
}
What happens right now is this: the form is always submitted.
I want this behavior:
saveCode()
orsaveCode
.As @Bergi said earlier the best way to do this is to use event.preventDefault()
. So in order to achieve this you need some modification, first of all, it is better to set your event listener to the specific input
, then your remaining code for listening to the event should work fine. Then you need to use event.preventDefault()
inside your saveCode()
(And also after catching enter event) to prevent submitting form, but to make event
work as expected you need to avoid using return in your onclick
() method to allow event passing to the function automatically.return saveCode()
Since there were some bugs in the previous method, I just add some modifications to it. Due to the saveCode()
reference error I moved above of all of its usage to prevent such a thing, then I removed onclick
events (They are not recommended at all it JS anymore) and then add an event listener for submitting event instead.
So your final code should be something like this (If saveValue()
is existed and work as well):
var codeField = document.getElementById("fcode");
function saveCode() {
console.log("saveCode is running!");
saveValue(value);
codeField.value = "Submitted";
return false;
}
document
.getElementById("fcode")
.addEventListener("keydown", function(inEvent) {
if (inEvent.keyCode == 13) {
// enter
inEvent.preventDefault();
if (this.value === "") {
return false;
} // do nothing
saveCode();
return false;
}
});
document
.getElementById("formCode")
.addEventListener("submit", function(inEvent) {
event.preventDefault();
var value = codeField.value;
if (value === "") {
return false;
}
saveCode();
});
<form id="formCode">
<label for="fcode">Type Code:</label><br>
<input type="text" id="fcode" name="fcode" autofocus /><br>
<input type="submit" value="Submit – Enviar" />
</form>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments