Submitting Form on Enter Press - javascript

I know that this question has been asked before but I'm having particular trouble submitting my form when I press the enter key. I've tried multiple solutions but none have worked. When I try to press enter, the page refreshes and my typing is gone.
This is my HTML:
form class="nput">
<h1 class= "header">Member Login</h1>
<label class="text" for="pswd">Enter your password: </label>
<input class="form" type="password" id="pswd">
<input id="yeet" class="bttn" type="button" value="Submit" onclick="checkPswd();" />
</form>
And this is my Javascript:
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "password";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location="members.html";
}
else{
alert("Password incorrect. Please try again.");
}
}
// Get the input field
var input = document.getElementById("pswd");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
alert("hi there");
event.preventDefault();
document.getElementById("yeet").click();
}
});
</script>
I cannot figure out this small issue and I would appreciate any help! Thanks!
EDIT: I just wanted to let everyone know that I do in fact know that there is little security that comes with this method but I mostly want the password for looks not function.

You got something backwards there - you are submitting the form with Enter. This is exactly the problem though, it seems as if you don't want to submit it, instead you want to run your client-side handler checkPswd. (You do know that everyone can read the correct password in their browser console though, right? So it's no protection.)
What you want to do is change the onclick on the button to an onsubmit on the form itself! Then your code will run no matter in what way (keyboard or mouse) the form is submitted.
You can delete the whole keyup stuff then.
(The reason your attempt to "click" the button in JavaScript wasn't working is because unlike jQuery's click method, the vanilla click will only execute the default action and not any attached click event handlers like yours. Also, it is kinda backwards because you should react on the common ground of both clicking the button and pressing Enter, which is submitting the form.)

To echo a comment above - you want to use the onsubmit handler on the <form> element - this will allow users to submit the form both by clicking the <button type="submit> button, and by hitting the enter key in one of the forms <input> elements.
You can probably ditch the input.addEventListener("keyup", function(event) {...} altogether by just using the obsubmit handler.
You can learn more about the HTML <form> element's onsubmit behavior here:
https://www.w3schools.com/tags/ev_onsubmit.asp

No need to put handlers on button element. You should use either input type as submit or button type as submit. onsubmit handler can be given to form element where you can actually prevent default event and go ahead with password validation .
Hope this gives you an idea.

If I were you, I would do two things:
1) I would check the Chrome debugger to see if there are any issues with your code
2) Instead of input.addEventListener("keyup", function(event) {, I would try input.onkeyup = function(event) { and see if that works.
Hope this helps.

Related

HTML text box and button that redirects user to a page of same name not working when <form> is added

Below is a code that redirects people to a page of the same name. For example, if I type in the word 'chocolate' and click 'Submit', the user should be redirected to a page of the same name called 'chocolate.html', etc.
This code only works when the <form> parameter tag is removed, and if removed involves manually clicking the [Submit] button to be redirected to the .html page of the same name (rather than redirecting when pressing [Enter] or [Return] key on the keyboard).
This code does not work when I add the <form> parameter tag; it only works if removed. I've been meddling with this for hours to get it to work with the <form> tag. Any ideas?
This is the code:
Note: If you remove the form tag, it works, but only when you click the 'Submit' button manually.
This is what I got so far, I now only need the button to automatically click when the person presses the Enter key on their keyboard. :)
UPDATE: Firstly, thank you so kindly for your help so far.
UPDATE: The code now successfully redirects to a .html page of the same name, but the user needs to manually clicks the [Submit] button to accomplish this. From here, I am simply needing to find a way of having the [Enter] button automatically be selected/clicked whenever the user presses [Enter] on their keyboard. :)
<input id="test" type="text" autofocus>
<button type="button" onclick="redirect()">Submit</button>
<script>
function redirect()
{
var url=document.getElementById('test').value
window.location = url+".html"
}
</script>
Add a type attribute to your button like so:
<button type="button" onclick="redirect()">Submit</button>
By default, if not set, the type of a button is assumed to be submit and will therefore submit your form to the action provided in the form's action attribute. Setting the type attribute to button prevents this default behaviour.
Seeing that you have no action attribute specified in your form, the current page is assumed as the action to redirect to so the form essentially reloads the current page.
This is something new. Anyway the thing is when you are keeping the form tag there it is with no action attribute keeping you in the same page. When form tag is there you can not hit the script for the redirect.
When you are removing the form tag it is hitting the JS and activating the code. Seeing the form tag I am assuming that you are trying to send some data.
It is advised that you use jquery and ajax to manipulate these data. Or you can discuss more.
Add this after your function:
var test_keydown = document.getElementById("test");
test_keydown.addEventListener("keydown", function (e) {
if (e.code === "Enter") { //checks whether the pressed key is "Enter"
redirect();
}
});
I got your problem, basically, you want to trigger redirect function when the user clicks submit button or if the user presses the ENTER key on the keyboard.
You can do this 2 ways -
If you want the user to redirect when he press enter key anywhere on the page, then you need to add keyup event on the document object, see below code -
It will trigger redirect function when the user clicks the ENTER key on the keyboard.
<input id="test" type="text" autofocus>
<button type="button" onclick="redirect()">Submit</button>
<script>
function redirect()
{
var url=document.getElementById('test').value
window.location = url+".html"
}
document.addEventListener("keyup", function(event) {
if (event.keyCode === 13) { //13 is enter keycode
event.preventDefault();
redirect();
}
});
</script>
Another way is to add keyup event on the input itself and then call the redirect function. This is when you don't want to trigger redirect on the whole document, but only when the user is done typing in input and then presses ENTER.
<input id="test" type="text" autofocus onkeyup="handleKeyUp(event)">
<button type="button" onclick="redirect()">Submit</button>
<script>
function redirect()
{
var url=document.getElementById('test').value
window.location = url+".html"
}
function handleKeyUp(event) {
if (event.keyCode === 13) { //13 is enter keycode
redirect();
}
}
</script>
If you want to do this in form tags handle the on submit event instead. This will also handle the enter keypress at the same time as that is the default behavior in a form.
//Add the evnent listener unobtrusivly
document.getElementById("redirector").addEventListener("submit", function(event) {
//Stops the form submitting (its' default action)
event.preventDefault();
//Get the location
var redirectTo = document.getElementById('test').value + ".html"
//bit of debugging
console.log("Redirecting to: " + redirectTo)
//redirect
window.location.href = redirectTo;
})
<form id="redirector">
<input id="test" type="text" autofocus>
<!-- Note this will now submit -->
<button>Submit</button>
</form>
You should use
document.addEventListener('keyup',function(e) {submitButton.click()})// submitButton is `document.getElementById('<idOfsubmitButton>')`

Prevent form submit on enter VueJS/Semantic UI

Have been searching for a solution to this problem for 2 days now and none of the suggested solutions have worked so far.
My form html is defined with
<form id="quote_form" action="" method="get" class="ui large form">
and input text fields in the form
<input v-model="city" type="text" name="quote[city]" id="city">
I have been trying to isolate the cause of the issue but have not been able to do so. I tried turning off the keyboard shortcuts settings for semantic ui forms:
$('.ui.form').form({
keyboardShortcuts: false
});
I have also tried to override the enter key and prevent it from triggering the submit function in these ways:
$('#quote_form').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.stopPropagation();
e.preventDefault();
return false;
}
});
$(document).on("keypress", "form", function(event) {
return event.keyCode != 13;
});
$('#quote_form').bind('keypress keydown keyup', function(e){
if(e.keyCode == 13) { e.preventDefault(); }
});
The form has multiple steps in filling it in. Each step uses a button to permit the advance to the next step. When enter is pressed then it causes the form to redirect to the first step/tab of the form. The only case where it doesn't redirect is when the rules of the current step are not satisfied. The form submission is handled by a submit button where the button itself calls methods to validate and submit the form. I can't find any connection between enter submit behaviour and the button for submitting.
If I am missing any useful information to help isolate the cause then please let me know. I'm new to asking questions here and want to prevent my question from being considered bad as much as possible :)
Here is solution for you:
#submit.prevent
https://jsfiddle.net/4qpffycs/2/
Just use #keyup.enter.prevent at the end of the input markup. See VueJS Doc
By the way, you should try to use native VueJS Events instead of all redoing it with JQuery
The solution I found regards only Semantic UI without VueJS, but should be applicable here and gives a bit of an insight into the issue.
The problem arises from the fact that $("#formId").form({ ... }) registers an event handler for a button press and submitting the form on Enter press if one of the input boxes are selected. This can be seen in Chrome DevTools when selecting the element and choosing Event Listeners category:
The simplest way I found to remove this behavior is to call
$("#formId").unbind('keydown')
to remove the keydown bind completely from the element.

How to display require popup manually?

I'm trying to display the require popup when a certain input is not filled or isn't filled correctly in my form. So, for doing this, I've created this form:
<form id="login">
<input class="form-control require" type="email" placeholder="username" ></input>
<button type="submit">
go
</button>
</form>
and I put the logic inside a js function:
$('#login').submit(function(event)
{
event.preventDefault();
$(event.target).find('.require').each(function()
{
if($(this).val().length == 0)
{
this.setCustomValidity("Field Required!");
}
else
{
this.setCustomValidity('');
}
});
console.log('ajax execution');
});
Now how you can see when the form is submitted I prevent the default event submit, and assign to each control a custom validation error. Now the problem's that if a field is not valorized correctly, for example is blank I get no popup displayed, instead, if I press again the submit button I can see the require popup appear on the UI.
Someone could help me to fix this?
I put an example JSFIDDLE here.
When you press the button for the first time no popup appear, the second time appear correctly but, this should appear the first time or anyway, each time that a particular field is not valid.
if($(this).val().length == 0) this code will not properly if the input field has only space . To avoid that u should use this:
if($.trim($(this).val()).length == 0)
OR
if($.trim($(this).val()) == "")
Your problem seems to be that the submit event is only firing once. I'm not familiar with bootstrap, so I haven't seen the setCustomValidity function before but I would guess that it is probably attaching its own listener, which is prevent the button click from triggering the submit at all.
I notice that if I type something into the text box, and fire setCustomValidity on it, it says "please enter an email address" - which I don't see in your code. If I then enter 'asdf#qwer.dfsgh', it gets validated and submits.
So it looks like you have not understood how setCustomValidity is supposed to be used. I would guess, you are probably supposed to attach it once, when the page first loads, and not repeatedly as you are doing.

Bootstrap form input: prevent submit, but allow for input checking

I've got the following problem:
I use bootstrap form to take input from users, and I use jQuery preventDefault() to disable the submit button from sending the form (I use AJAX instead). However, that function also prevents input checking that is done by bootstrap. For example, if someone enters an e-mail without '#' into
<input type="email" class="form-control">
bootstrap would, upon clicking submit, check that input and return a popup with an error.
My question is: how to prevent the request being sent while keeping the bootstrap form checking mechanism intact?
What I have tried: using preventDefault() and writing my own checking script, however this seems like reinventing the wheel and having extra code when it's not needed.
Thank you!
I believe you are talking about the native HTML5 form validation and not validation by bootstrap its self, I have never come across bootstrap validation before. (i may be wrong though).
Most new browsers will validate <input type='email'/> as an email address and <input type='text' required='required'/> as required on form submission.
If for example you are using e.preventDefault(); on the click event on the submit button the form will never attempt to submit and hence the native validation will never happen.
If you want to keep the validation you need to use e.preventDefault(); on the submit event of the form not the click event on the button.
The html...
<form action='' method='post'>
<input type='email' name='email' required='required' placeholder='email'/>
<button type='submit'>Submit</button>
</form>
The jQuery...
//this will stop the click on the button and will not trigger validation as the submit event will never be triggered
$("button").on('click',function(e){
e.preventDefault();
//ajax code here
});
//this will stop the submit of the form but allow the native HTML5 validation (which is what i believe you are after)
$("form").on('submit',function(e){
e.preventDefault();
//ajax code here
});
Anyway hope this helps. If I have misunderstood in any way let me know and ill try to assist further.
I had the same issue, I came to use "stopPropagation" as the way to stop the form submission. But after a little reading on jQuery 3, I realized that "preventDefault" was enough to what I wanted.
This caused the form validation to happen and the submit event didn't proceed.
(This example is of an attempt i had on my own).
$('form').on("submit",function( event ) {
if ( $('#id_inputBox_username').val().length == 0 &&
$('#id_inputBox_password').val().length == 0 ) {
event.preventDefault();
$('#id_inputBox_username').tooltip('show');
$('#id_inputBox_password').tooltip('show');
} else if ( $('#id_inputBox_username').val().length == 0 ) {
event.stopPropagation();
$('#id_inputBox_username').tooltip('show');
} else if ( $('#id_inputBox_password').val().length == 0 ) {
event.stopPropagation();
$('#id_inputBox_password').tooltip('show');
}
});
I had the same problem and I find this solution:
$('#formulario').on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
e.preventDefault(); //prevent submit
$(".imprimir").show();
$(".informacao").fadeOut();
carregardados();
}
})

When editing a text input, how do I do a specific JavaScript action on hitting "Enter" key without the form's onSubmit handler?

I have an HTML input text field.
How can I perform a specific JavaScript call when hitting "Enter" button while editing that field? Currently, hitting "Enter" reloads the entire page, presumably due to submitting the entire form.
NOTE: This HTML/JS code is merely included as a portlet into a large HTML page for a portal, which has one large master form wrapped all the way around my code. Therefore I can not control the form - can't change onSubmit event or action or wrap my INPUT field into a smaller form - otherwise the solution would be obvious :)
Also, a solution that does not involve adding a visible button to the form is strongly preferable (I don't mind adding a button with display:hidden if that's what it takes, but my attempt to do so didn't seem to work).
This needs to be straight up JS - no Query/Prototype/YUI is available.
P.S. it's a search field and the action will be a call to an existing in-page JavaScript search method, if someone's curious.
Thanks!
Assuming you have a text input something like
<input id="myTextBox" name="foo" value="bar">
... you could do something like this, after the document has loaded, and it will work in all mainstream browsers:
document.getElementById("myTextBox").onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
if (charCode == 13) {
// Suppress default action of the keypress
if (evt.preventDefault) {
evt.preventDefault();
}
evt.returnValue = false;
// Do stuff here
}
};
Include the following javascript
<script type="text/javascript">
function noenter() {
return !(window.event && window.event.keyCode == 13);
}
</script>
Add the following attribute into the input element that you wish to prevent the submit
onkeypress="return noenter()"
Of course you can perform some other event if you wish...
Would you be better off using the document object to detect the Enter action? That way you need make no changes to the HTML form tags. You can assign the search function to the button, although if it's hidden I am not sure how the user would click on it, or you could use something like onblur to capture the user tabbing out of the input control.
Try adding an attribute "action=javascript:void(0)" as in the example below.
Enter will trigger the same action as clicking on the submit button, but won't reload the page automatically.
<html>
<head></head>
<body>
<div id="status"></div>
<form action="javascript:void(0)">
<input type="text" />
<input type="submit" value="submit" onclick="document.getElementById('status').innerHTML = 'submitted';"/>
</form>
<script>document.getElementById('status').innerHTML = 'page loaded';</script>
</body>
</html>

Categories