Unable to submit form on keypress - javascript

i want to submit a form with and enter key stroke when the user enters a username and password.I get an alert coming back from my function when the enter key is pressed.But after that it doesnt submit the form. What am i doing wrong?
<form id="myForm" action="#" onsubmit="return false;" >
<div>
<input type="text" id="username" />
</div>
<div>
<input type="password" id="password" />
</div>
<div>
<button type="submit" id="btnLogin" onclick="myFunction(0)">Log in</button>
</div>
<script type="text/javascript">
function myFunction(e) {
if ((e && e.keyCode == 13) || e == 0) {
alert("The form was submitted"); // this alert gets called,but my form doesnt get submitted
document.forms.myForm.submit();
}
}

You can use like this.(Use jquery)
1.Change Input type submit to button
2.Change the code for submitting form
3.Write a keyPress event for the form
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="test.html" >
<div>
<input type="text" id="username" />
</div>
<div>
<input type="password" id="password" />
</div>
<div>
<button type="button" id="btnLogin" onclick="myFunction(0)">Log in</button>
</div>
</form>
<script type="text/javascript">
function myFunction() {
alert("form submitted");
document.getElementById("myForm").submit();
}
$('#myForm').on('keydown', function (e) {
if (e.which === 13) {
myFunction();
}
});
</script>

1) Remove return false from the form onsubmit event.
2) Remove onclick event from the button.
3) Using JS, bind a submit event to the form and do what you need in the event handler, as below:
var loginForm = document.getElementById('myForm');
loginForm && loginForm.addEventListener('submit', myFunction);
function myFunction(event) {
event.preventDefault();
alert("form is about to be submitted...");
loginForm.submit();
}
<form id="myForm">
<div>
<input type="text" id="username" />
</div>
<div>
<input type="password" id="password" />
</div>
<div>
<button type="submit" id="btnLogin">Log in</button>
</div>
</form>
Even better, remove all the JS and keep only the form as in my answer. It would submit the form on enter as that's the default behaviour when there is a button/input with type submit!

You can try this without checking keyCode. You can enter key from any input fields or button inside the form.
function myFunction(e) {
var username = e.target.querySelector('#username');
var password = e.target.querySelector('#password');
if(username.value && password.value){
alert("The form was submitted");
return true;
}
return false;
}
<form id="myForm" action="#" onsubmit="return myFunction(event)">
<div>
<input type="text" id="username" />
</div>
<div>
<input type="password" id="password" />
</div>
<div>
<button type="submit" id="btnLogin">Log in</button>
</div>
</form>

I dont think you really need javascript for this as realistically pressing enter inside a form will usually submit the form.
Notice in the example below that all we are really doing is targeting
the submit event for the form and this also includes hitting the enter
key.
However to satisfy your question
Using jQuery you could try binding the keypress event to the button click submit event.
Something like this:
$("#btnLogin").blur();
$('#btnLogin').focus().click();
p.s. remember to close your <form> tag with </form>
Example
$('#myForm').submit(function() {
var confirmSubmit = confirm("Submit the form?");
if(confirmSubmit)
{
$("#btnLogin").blur();
$('#btnLogin').focus().click();
}
else
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="yourPage.html">
<div>
<input type="text" id="username" />
</div>
<div>
<input type="password" id="password" />
</div>
<div>
<button type="submit" id="btnLogin">Log in</button>
</div>
</form>

Related

Getting value from submitted form

I have a form with 2 buttons (type="submit"). Each of them has different value.
$(document).ready(function() {
$('#myform').submit(function() {
var _att = $(this).attr("value");
if (_att == "insert") {
//do insert here ....
}
if (_att == "update") {
//do update here ....
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="email" name="email" placeholder="Enter email" /><br>
<button type="submit" value="insert">Insert Button</button>
<button type="submit" value="update">Update Button</button>
</form>
My question is, how to get value from clicked button in the submitted form?
I tried by trying to get attr("value") but the return value is undefined.
You should handle the click event on [type="submit"] to get their attr("value"), i.e.
$(document).ready(function() {
$('[type="submit"]').on('click', function(event) {
event.preventDefault();
let value = $(this).attr("value");
console.log(value);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="email" name="email" placeholder="Enter email" /><br>
<button type="submit" value="insert">Insert Button</button>
<button type="submit" value="update">Update Button</button>
</form>
N.B. Remember to prevent their default behavior (with event.preventDefault).
You can achieve this easily by using a unique class .submit-button on your button
I have also added preventDefault function which will ensure that your page is not refreshing on form submit button clicked and check for all the validations - if any accordingly.
Run snippet to see it working below.
Working Demo: https://jsfiddle.net/xo3pkqf9/
$(document).ready(function() {
$("#myform button").click(function() {
//Check which button was clicked
if ($(this).attr("value") == "insert") {
//Form Submits
alert("Insert Clicked - Form will submit")
$("#myform").submit();
}
if ($(this).attr("value") == "update") {
alert("Update Clicked - Form will submit")
//Form Submits
$("#myform").submit();
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="email" name="email" placeholder="Enter email" required/><br>
<button type="submit" value="insert">Insert Button</button>
<button type="submit" value="update">Update Button</button>
</form>

How can I submit a form when the user presses the `Insert` key?

How can I prompt for confirmation before submitting a form after they press the Insert key, and submit the form without confirmation when the user pushes the Enter/Return key ?
Summary of actions intended
INSERT : Prompt for confirmation. Submit form if confirmed.
ENTER : Submit form.
I have the following html form :
<form action="hhhhhhh.php" method="post" >
<input type="text" name="DatInvNew"/>
<input type="text" name="SumInvNew"/>
<input type="text" name="KolInvNew"/>
<input type="submit" value="next"/>
</form>
Here is the answer..
Try it once, Just copy and past it..
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('#inputform').on('keydown', 'input', function (event) {
switch(event.which) {
case 13: // enter
event.preventDefault();
var $this = $(event.target);
var index = parseFloat($this.attr('data-index'));
$('[data-index="' + (index + 1).toString() + '"]').focus();
break;
case 45: // insert
$('#click-to-submit').trigger('click');
break;
}
});
});
</script>
<form id='inputform' action="hhhhhhh.php" method="post">
<input type="text" name="DatInvNew" data-index="1" />
<input type="text" name="SumInvNew" data-index="2" />
<input type="text" name="KolInvNew" data-index="3" />
<input type="submit" value="next" class="click-to-submit" id="click-to-submit" />
</form>
The following example does these things (as per the original question) :
INSERT : Prompt for confirmation. Submit form if confirmed.
ENTER : Submit form.
document.onkeypress = function (e) {
e = e || window.event;
if(e.keyCode == 45) {
if(confirm("Would you like to submit this form?")) {
document.getElementById("myForm").submit();
}
} else if (e.keyCode == 13) {
document.getElementById("myForm").submit();
}
};
And change your html slightly :
<form action="hhhhhhh.php" method="post" id="myForm">
<input type="text" name="DatInvNew"/>
<input type="text" name="SumInvNew"/>
<input type="text" name="KolInvNew"/>
<input type="submit" value="next"/>
</form>

Password in confirm box Javascript

I have a Delete button in my PHP page which deletes a record.
But when I delete that button I do a confirm box with:
<form action="log.php" method="post" onsubmit="return confirm('Are you sure?');">
Can I make it so when they confirm they have to fill in a password?
So what I mean is something like this
<form action="log.php" method="post" onsubmit="return confirm('password :');">
And then they have to fill in a password
Thanks in advance.
Hi You Need some thing like this, Modify according to your requirements
<script>
function do_check()
{
var return_value=prompt("Password:");
if(return_value==="your_password")
return true;
else
return false;
}
</script>
<form action="log.php" method="post" onsubmit="return do_check();">
Try using input type="password" , required attribute` ; disable submit until password set
document.forms["form"].querySelector("input[type=button]").onclick = function(e) {
e.preventDefault();
this.nextElementSibling.disabled = false;
this.nextElementSibling.nextElementSibling.disabled = false;
}
<form name="form">
<input type="button" value="Are you sure?" />
<input type="password" minlength="3" maxlength="7" required disabled />
<input type="submit" disabled />
</form>
document.forms["form"].querySelector("input[type=button]").onclick = function(e) {
e.preventDefault();
this.nextElementSibling.disabled = false;
this.nextElementSibling.nextElementSibling.disabled = false;
}
<form name="form">
<input type="button" value="Are you sure?" />
<input type="password" minlength="3" maxlength="7" required disabled />
<input type="submit" disabled />
</form>

JavaScript link error

I am using JavaScript to validate email. The problem is, when the email ids don't match, then one alert button will come. Once I click the button it still takes me to the other page, instead of same page to correct my mail id.
HTML:
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="validate()">
JavaScript:
function validate()
{
if(document.getElementById("email").value != document.getElementById("confirm_email").value)
alert("Email do no match");
}
You need to tell the submit button to not perform the submit
function validate()
{
if (document.getElementById("email").value!=document.getElementById("confirm_email").value) {
alert("Email do no match");
return false;
}
}
The problem is because You have taken button type=submit
Change input type='button'
<input type="button" name="submit" value="submit" class="button" onClick="validate()">
and submit form using javascript
document.getElementById("myForm").submit();
I case you want to validate only on submit then use
event.preventDefault();
and then validate but after successful validation you have to submit the form using js or jq. JS method is given above and jq method is:
$("form").submit();
You should add return false; in your if code block if you dont want the redirect.
Its the browser's default to refresh the page when the form is submitted. To prevent this refresh, add return false;.
Learn more: return | MDN
<html>
<head>
<script>
function validate(){
if(document.getElementById("email").value != document.getElementById("confirm_email").value){
alert("Email do no match");
return false;
}
}
</script>
</head>
<body>
<form action="formsubmit.php" method="post" onsubmit="return validate()">
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button">
</form>
</body>
</html>
Use the below javascript code, your html code is correct!
Well executing the JavaScript code in StackOverflow Script Runner won't run and occur erorrs. If input boxes with email and confirm_email id(s) are declared, this should work.
Hope it could help!
function validate(){
if(!document.querySelector("#email").value === document.querySelector("#confirm_email").value){
alert("Email do not match.");
}
}
/* In JavaScript, the ! keyword before the condition belongs to execute the statement if the given condition is false. */
It must prevent the form to get submitted if the validation is failed. so
return validate();
must be there. So if the validate function returns a false value then it will stop the form to be submitted. If the validate function return true then the submission will be done.
<form method='post' action='action.php'>
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="return validate();">
</form>
<script>
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate(){
if(!validateEmail(document.getElementById('email').value))
{
alert('Please enter a valid email');
email.focus();
return false;
}
else if(document.getElementById('email').value!=document.getElementById('confirm_email').value) {
alert('Email Mismatch');
confirm_email.focus();
return false;
}
return true;
}
</script>
Fix that and remove type=submit and use a function or use following code:
<script>
function check(){
//* Also add a id "submit" to submit button*//
document.querySelector("#submit").addEventListener("click", function(){
//* Perform your actions when that submit button will be clicked and close with this in next line*//
})</script>

JavaScript custom validation not working

Here is my code :
<script type="text/javascript">
function submitform() {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
as expected, the form when submitted should call the submitform function, and if the name field is blank, it should return false and give an alert.
But, it just goes through.
Any explainations?
You need to call the function with return, so that the false value prevents default action (form submission)
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to stop a little.
You can use onSubmit, but it's best to delete your input submit and put a button.
Then on button click you can do what you want and eventually submit the form
Form:
<form action="mail.php" method="post" id="mailForm">
<input type="text" id="name" name="name" placeholder="name">
<button id="submitMailForm">Submit</button>
JS:
$( document ).on( "click", "#submitMailForm", function(e) {
//My control Here
//If all ok
$("#mailForm").submit();
});
You can use jquery instead of javascript for this kind of validation is will be very easy to implement.
<form action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit" id="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(fucntion(e){
if($("#name").val() == ""){
alert("Name is empty");
e.preventDefault();
}
});
});
</script>
And dont forget to add jquery library before the script tag.
You need to change your onSubmit attribute as follows
onsubmit="return submitform();"
So your html look like this
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
To cancel submission, the listener needs to return true or false. Also, if the function validates the fields, far better to name it for what it does rather than when it does it so call it something like "validateForm".
Also, giving a control a name of "name" masks the form's own name property. While that doesn't matter here, in general it's not a good idea to give any form control a name that is the same as a standard property of a form (e.g. "submit" or "reset").
So you might end up with something like:
<script>
function validateForm(form) {
if (form.personName.value == '') {
alert('Please enter a name');
return false;
}
}
</script>
<form ... onsubmit="return validateForm(this);">
<input type="text" name="personName">
<input type="submit">
</form>
<script type="text/javascript">
function submitform(event) {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
event.preventDefault();
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform(event);">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to prevent default of submit. In JS return false does not stop the propagation of the "submit" function (with frameworks can be different).
I suggest you to read:
event.preventDefault() vs. return falseenter link description here
just try this script
function submitform() {
var x = document.forms["fname"].value;
x = x.trim(); // Remove white spaces
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}

Categories