What event is triggered if form is submitted by pressing enter? - javascript

I have a simple form like this:
<form>
<div>Name:</div>
<input name="firstname" id="typeTracking" type="text">
<input value="Submit" id="submitTracking" type="submit">
</form>
And some vanilla JS code to detect when the form is submitted:
document.addEventListener('submit', doFancyThings);
But the doFancyThings function is only triggered if I click the submit button, not if I press the enter key on my keyboard. How can I, using only plain javascript, listen for the enter key submit event, to also trigger my doFancyThings function?
I've had a look in the Event reference at MDN and as far as I understand the submit event is only triggered when "The submit button is pressed". However, as the form is undoubtly submitted on enter key press, it ought to be firing some sort of event too, I reckon.
According to submit - Event reference the "event is fired only on the form element, not the button or submit input." Which sounds a bit contrary to the previous quote, and even less understandable why my listener doesn't trigger on the enter key.

not if I press the enter key
Use a form
document.addEventListener('submit', doFancyThings);
function doFancyThings(e) {
console.log('Enter pressed')
e.preventDefault()
}
<form>
<div>Name:</div>
<input name="firstname" id="typeTracking" type="text">
<button value="Submit" id="submitTracking" type="submit">Click</button>
</form>

try this
var form = document.querySelector("form");
form.onsubmit = function(e) {
doFancyThings();
e.preventDefault(); // for preventing redirect
};
form.onkeydown = function(e) {
if (e.keyCode == 13) {
doFancyThings();
e.preventDefault(); // for preventing redirect
}
};
function doFancyThings() {
alert("hmmm");
};
<form>
<div>Name:</div>
<input name="firstname" id="typeTracking" type="text">
<input value="Submit" id="submitTracking" type="submit">
</form>

Related

Trigger submit on pressing enter (as well if submit button is clicked)

I know this has been asked before, and I have read the replies carefully, but still cannot get it to work in my code.
This is what I would like to achieve:
there is a text input field. The user types in the field. On clicking 'submit' button, the word 'done' appears on the screen. I can do this part without difficulty. However, I also want the user to able to submit by hitting 'enter' when they are in the input field, instead of having to hit 'submit' button (although I still want the submit button to work also - basically user has two options on how to submit, by clicking submit button, or hitting enter).
I followed instructions on W3, and have the following code:
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("submit").click();
}
});
function myFunction() {
document.getElementById("demo1").innerHTML = "done";
}
<div class = 'method'>
<form id="myFunction">
<h3>myFunction():</h3>
<input id="myInput" name="name">
<button id="submit" type="button" onclick="myFunction()">Submit</button>
<div id="demo1">function result on submit goes here</div>
</form>
</div>
What am I missing?
Thanks in advance
By using a <button type="submit"> instead of type="button", you won't need the javascript to detect a keystroke. Both hitting the submit button and pressing enter will cause the onsubmit event to fire on the form. By calling event.preventDefault(), you make sure the browser does not navigate after submitting the form.
function myFunction(event) {
event.preventDefault();
document.getElementById("demo1").innerHTML = "done";
}
<div class='method'>
<form id="myFunction" onsubmit="myFunction(event)">
<h3>myFunction():</h3>
<input id="myInput" name="name">
<button type="submit">Submit</button>
<div id="demo1">function result on submit goes here</div>
</form>
</div>
You dont need to add event listeners to your button or your input.
Instead add the event listener to your form and prevent default event, because forms can be submitted by both 'enter' key as well as submit buttons (button needs to be of type 'submit').
document.getElementById('myFunction').addEventListener('submit', myFunction)
function myFunction(e) {
e.preventDefault();
document.getElementById("demo1").innerHTML = "done";
}
<div class='method'>
<form id="myFunction">
<h3>myFunction():</h3>
<input id="myInput" name="name">
<button id="submit" type="submit">Submit</button>
<div id="demo1">function result on submit goes here</div>
</form>
</div>
You can simplify your code to listen for the submit event, which will trigger when the form is submitted by hitting enter or by clicking the submit button:
var input = document.getElementById("myInput");
var form = document.getElementById( "myFunction" );
form.addEventListener( "submit", function( e ){
e.preventDefault();
document.getElementById( "demo1" ).innerHTML = "done";
});
<div class='method'>
<form id="myFunction">
<h3>myFunction():</h3>
<input id="myInput" name="name">
<button id="submit" type="submit">Submit</button>
<div id="demo1">function result on submit goes here</div>
</form>
</div>

Check Required Fields With preventDefault

I ran into a situation where I have a HTML form and it has required on many of the fields. The issue is I have to use preventDefault which ignores 'required' inputs and submits the form even without the required fields. Because the work is not entirely up to me I must use preventDefault and work around it.
I am working with jQuery and I am trying to find a way to target the fields that have required and prevent the form from submitting on click.It is important that the required fields are filled out on the form before a user can submit the form as I do not want required information missing when it is being submitted. Help is appreciated!
HTML
<form id="myForm">
<input type="text" name="sentence1" id="st1" placeholder="Text here" required>
<input type="text" name="sentence1" id="st2" placeholder="Text here" required>
<input type="text" name="sentence1" id="st3" placeholder="Text here" required>
<input type="text" name="sentence1" id="st4" placeholder="Text here" required>
<input type="text" name="sentence1" id="st5" placeholder="This field is not required">
<button type="submit" id="submit-form">Submit</button>
</form>
Came across the same problem and here is the solution that works for me.
Form elements have a function called checkValidity and reportValidity. We can use these and override the click event for the submit button.
$('#submit-form').click((event) => {
let isFormValid = $('#myForm').checkValidity();
if(!isFormValid) {
$('#myForm').reportValidity();
} else {
event.preventDefault();
... do something ...
}
});
In your event handler, where you are using preventDefault(), add the checkValidity() method on the form element:
document.getElementById('myForm').checkValidity();
This will "statically" check your form for all HTML5 constraint violations (including required),
Just a quick solution for your problem. I hope this is what you need. Check below:
$('#submit-form').click(function(){
event.preventDefault();
if(validateForm()){
alert('sending');
}
});
function validateForm() {
var isValid = true;
$('input[type=text]').each(function() {
if ( $(this).val() === '' ) {
alert('validation failed');
isValid = false;
}
});
return isValid;
}
Or visit JSFiddle: enter link description here
You can use preventDefault() in forms submit method. Then 'required' will work.
document.querySelector('form').addEventListener('submit', submitHandler);
function submitHandler(e){
e.preventDefault();
//your code here
}

mvc - submit text input field when enter

I'm trying to use "Enter" in a text input field to submit the message (in SignalR chat). I've tried hundreds of methods, but can't seem to get it working.
I either wanna have it so when I press enter it clicks the btn or presses tab then enter.
here is the input and btn
<input class="form-control" id="message" maxlength="200" />
<input type="button" class="btn btn-default" id="sendmessage" value="Send" />
Change
<input type="button" ...
To
<input type="submit" ...
or
<button type="submit" ...
See also button type documentation.
If you don't want to use form submit, you can define the logic in javascript,
document.getElementById("message") // to get the text box
.addEventListener("keyup", function(evt) { // Keyup -> Any key pressed
if (evt.keyCode == 13) { // 13 for enter
document.getElementById("sendmessage").click();
}
});
For keycodes, you can refer this site

function in onsubmit not executing in javascript form

Whenever I press the submit button it just submits the form and doesn't seem to run the checkSubmit function. Everything I've looked at in other examples suggests my code is correct. Is there something missing or wrong with the way I'm calling it?
<script language="javascript" type="text/javascript">
function checkSubmit() {
alert("This is an alert!");
if (document.getElementById("userID").value.length <1) {
alert("Please enter a User ID.");
return false;
}
else {
alert(document.getElementById("userID").value.length)
return true;
}
</script>
<form name="submitform1" method="POST" action="http://127.0.0.1/MyFile.php" onsubmit="return checkSubmit();">
Enter User ID: <input id="userID" name="userID" type=text size="25"/><br />
<input type="submit" name="submit" onclick="this.form.onsubmit();" value="Submit" >
</form>
<br />
Your code is missing the closing curly bracket for the checkSubmit() function for one.
In your HTML change the remove the onsubmit handler from the form element and change the onclick attribute on the submit button to call the function:
onclick="checkSubmit(event);"
Then, in your function, prevent the form from submitting, do your checks, then submit the form.
function checkSubmit(e) {
e.preventDefault();
// do checks
document.submitform1.submit();
}

Enter key to submit form with javascript in case of multiply form with php id

I have separate reply form with each post with it's own php $id in same page. So I want to submit each reply with keyboard Enter key. I collect this javascript code below from here, but I cannot understand how apply it for each reply.
B.N: Collected code not working also.
my form:
<form action="" method="post" class="repfrm'.$id.'" id="prepfrm">
<textarea name="replycom" id="replycom'.$id.'" class="replycom"></textarea>
<button type="submit" name="submit" id="'.$id.'" class="replyfrm">Post Reply</button>
</form>
Collected Script From stockoverflow:
$(".replycom").keyup(function(event){
if(event.keyCode == 13){
$(".replyfrm").click();
}
});
Something like that:
Bind keypress to textarea and submit the closest form when press the key
$("textarea").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$(this).closest("form").submit();
}
});
Change textarea to textbox and you press enter in textBox then it works which you want. Do not required jQuery code.
<form action="" method="post" class="repfrm'.$id.'" id="prepfrm">
<input type="text" name="replycom" id="replycom'.$id.'" class="replycom">
<button type="submit" name="submit" id="'.$id.'" class="replyfrm">Post Reply</button>
</form>
Try this script
$(".replycom").keypress(function (e) {
if (e.keyCode == 13) {
$(this).parents('form').submit();
}
});

Categories