Enter key doesn't activate button - javascript

I have a form with one field that the user needs to type into, and a button underneath that when clicked, does some jQuery and hides the login-form. But when I hit enter after typing something in, the page refreshes...
There's part of me that thinks it doesn't need to be an <input> or a <form>
I don't actually need to post anything. I have tried changing the input to a <button> which completely ruins my styling and still doesn't work. What's the best way of getting round this?
<div class="login-page">
<div class="form">
<form class="login-form" method="POST">
<!-- user inputs -->
<p class="phc">PHC:</p><input type="text" id="username" placeholder="Enter Your PHC Here" />
<!-- your submit button -->
<input class="login" type="button" id="submit" value="login">
</div>

True, Adam. If the form does not contain the type submit button, a keypress event has to be added manually. Otherwise Enter will act as the Accept Button on the form.

You need to attach keypress event to the form or at least the field. For convenience, you also need to combine the callback functions into one.
$('#username').on('keypress', function(event){
var code = event.keyCode || event.which;
if(code == 13){
// submit the form.
}
});
$('#username').on('keypress', function(event){
var code = event.keyCode || event.which;
if(code == 13){
console.log('Submitting form');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="login-form" method="POST">
<p class="phc">PHC:</p><input type="text" id="username" placeholder="Enter Your PHC Here" />
<input class="login" type="button" id="submit" value="login">
</form>

If the enter key is pressed when focused to an input field inside a form that has a submit button, the default browser behaviour is to fire a submit event on that form. You can prevent this happening by either:
return false;
or
e.preventDefault();
Full code:
$('.login-form').on('submit', function() {
return false;
});
Fiddle: https://jsfiddle.net/nc1e2gm6/
Bear in mind that if you go down the route of using e.preventDefault(); instead or return false;, you need to pass the e variable from the function call, like:
$('.login-form').on('submit', function(e) { ...

Don't think i explained it very well but i have fixed it, the enter key now activates the submit button rather than refresh the page.
$("form").submit(function() { return false; });
$(document).ready(function(){
$('#username').keypress(function(e){
if(e.keyCode==13)
$('#submit').click();
});
});

Related

Submit form only when submit button clicked and prevent "Enter" submitting form

I want to stop a user submitting a form upon clicking enter.
This works for that
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
However I have other buttons on the page that when I tab to and click enter to avail of their functionality, this is blocked via this function.
The button sits as so:
<input type='button' tabindex="29" value='Add Additional Drug' id='addButton'>
And I only want to submit the form when enter pressed while my submit button is selected.
<input type="submit" name="submit" value="Submit" tabindex="40" class="submit"/>
How would I do this?
EDIT
I see the answer in the attached Stackoverflow but he allow people to press Enter if they have completed all the fields:
I don't want a user to press Enter unless they have a button selected(i.e. Can't press Enter, tab to button, can press enter, which will trigger the button to do its functionality and not submit the form.
The form works on a Tabbing basis, so a user will tab over all the fields.
Binding the keydown event to the whole document will affect all inputs and forms on the page, you may have several ones in your page so it will mess up the whole page logic.
You can bind it to a specific form instead:
$("#myForm input").not("#addButton").keydown(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
Demo:
$("#myForm input").not("#addButton").keydown(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
form input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="myForm">
<input type="text" name="input1" />
<input type="text" name="input2" />
<input type="text" name="input3" />
<input type="submit" name="submit" value="Submit" tabindex="3" class="submit" />
</form>
Note:
I used #myForm as test id here to target a specific form in the
page, you just need to use your form id.
Using jQuery .not() method in .not("#addButton") won't affect the button with id="addButton".
First, keep in mind that what you are attempting breaks UI accessibility standards.
Bearing this in mind, you'll need to stop using a true "submit" button and use a regular button that impersonates the submit button.
Next, you'll need to manually trigger the click events for all non-submit button buttons via code.
Here's a working example. See the comments for details:
$(document).ready(function() {
$(window).on("keydown", function(event){
// Check to see if ENTER was pressed and the submit button was active or not
if(event.keyCode === 13 && event.target === document.getElementById("btnSubmit")) {
// It was, so submit the form
document.querySelector("form").submit();
} else if(event.keyCode === 13 && event.target !== document.getElementById("btnSubmit") ){
// ENTER was pressed, but not while the submit button was active
alert("Enter pressed on something other than submit button.");
// Cancel form's submit event
event.preventDefault();
// Invoke click event of target so that non-form submit behaviors will work
event.target.click();
// Tell JQuery to cancel the event
return false;
}
});
// Non-submit button event handling
$("#btnOther").on("click", function(){
alert("Other button clicked!");
});
// Set up your "regular" button to act as a "submit" button when it is clicked
$("#btnSubmit").on("click", function(){
// Submit the form
document.querySelector("form").submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action=# method=post>
<input name=test>
<input type=button id="btnOther" value="Other Button">
<input type=button id="btnSubmit" value=Submit>
</form>

Making a simple password checker in HTML/Javascript that displays a div upon correct password

I'm trying to make code for a simple password checker that will be part of a website I give to students for an activity. I don't care if the password is easy to find in the code. I just want the students to be able enter a password, and press enter or click the button to see if the password is correct.
This is the javascript:
<script type="text/javascript">
function isValid(){
var keyvalue = document.getElementById('keyvalue').value;
if (keyvalue == "miranda")
{document.getElementById('welcomeDiv').style.display = "block";}
else
{alert('ACCESS DENIED')}
}
</script>
The HTML
<form name="PasswordField" action="">
Type Password Below:</br>
<input type="text" id="keyvalue" name="keyvalue" onkeydown = "if (event.keyCode == 13) document.getElementById('subPass).click()">
<input type="button" id="subPass" value="ACCESS" onclick="isValid(this);">
</form>
<div id="welcomeDiv" style="display:none;" class="answer_list">
</br>
<p>ACCESS GRANTED</p></br>
Click to go to next stage.
</div>
Clicking the button works well, but if I press enter it will flash the hidden div briefly before reloading the page, thus hiding the div again. I'm trying to figure out how to prevent it from doing this.
Your action="" is probabaly not doing what you what it to.
Use `onsubmit="return false;"' instead:
<form name="PasswordField" onsubmit="return false;">
Type Password Below:</br>
<input type="text" id="keyvalue" name="keyvalue" onkeydown = "if (event.keyCode == 13) document.getElementById('subPass').click()">
<input type="button" id="subPass" value="ACCESS" onclick="isValid(this);">
</form>
Or just make it a <div instead of a <form
The button is submitting the form, reloading the page.
In the onclick attribute of your button you need to return false to override the browser's default behaviour of actually sending the form:
<input type="button" id="subPass" value="ACCESS" onclick="isValid(this); return false">
As Marvin mentioned in a comment you also need to fix the quotes in the onkeydown attribute of your text input and remove some extra spaces:
<input type="text" id="keyvalue" name="keyvalue" onkeydown="if (event.keyCode == 13) document.getElementById('subPass').click()">

How to submit form data in ajax using enter in the keyboard

I am creating a comment functionality and below are my code so far.
html
<form action="http://website.com/transaction_items/add_comment" class="" id="form-comment" role="form" method="post" accept-charset="utf-8">
<input type="hidden" name="checklists_item_id" value="6" style="display:none;">
<input type="hidden" name="user_id" value="1" style="display:none;">
<div class="input-group col-xs-12">
<input type="text" name="comment" value="" class="form-control" id="comment-input" placeholder="Enter your comments..">
<span class="input-group-btn">
<button class="btn btn-default" id="doc-comment" type="button">Post</button>
</span>
</div>
</form>
jQuery
This function is called when document is ready.
function comment () {
$('#doc-comment').click(function (e) {
var form_id = '#' + $(this).parents('form').attr('id');
// submit data from the form
submit.send(form_id);
});
}
The problem:
Using the button <button class="btn btn-default" id="doc-comment" type="button">Post</button> to submit data work fine, but
if I use enter in the keyboard, submit.send(form_id); will not do its function, instead the default form submission will execute.
How can I use ajax if use enter in the keyboard to submit form data?
nutshell
$("#form-comment").on('submit', function(evt) {
evt.preventDefault();
// do your ajax stuff here
});
you can then toss the onclick button listener.. as this will handle the button submit as well
There are more ways to submit a form then simply pressing the submit button.
You need to:
Use the forms submit method
Keep the form from doing the full submit.
-
// This will catch the *enter* as well as the submit button
$("#form-comment").on('submit', function(evt) {
evt.preventDefault();
// You can then submit the form via ajax and update things as needed.
});
IF you are going to use a button you should at least do a
<button type="button">...</button>
which behaves differently.
$("#form-comment").keyup(function (e) { // On pressing enter
if (e.keyCode == 13) {
// put your ajax code here
}
});
You may have to disable the default Enter event for the form submit button as well depending on your browser.
So in the Jquery Button click function make sure you have something like
event.preventDefault();

Simple Javascript login form

<form id="loginForm">
<p id="usernameLabel">Username:</p>
<input type="text" name="username" id="username" placeholder="username"/><br>
<p id="passwordLabel">Password: </p>
<input type="password" name="password" id="password" placeholder="password"/><br>
<input id="loginButton" type="submit" value="Login!" onsubmit="validateForm()">
</form>
<p id="loginMessage">Please Login!</p>
<script type="text/javascript">
function validateForm() {
var un = document.loginForm.username.value;
var pw = document.loginForm.password.value;
var username = "MitchWardle";
var password = "123abc456";
if ((un == username) && (pw == password)) {
window.location = "content.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
I have created a little login form on Javascript and I want it to navigate to Content.html when username and password are correct but when I click my Login button it just removes the text from the text box's, can anybody see whats wrong?
you need to return false to prevent default action of submitting the form , page gets refresh andyou loss your data, you can set type of submit button to
type="button"
or can change onsubmit to
onclick="validateForm(); return false; "
Just a couple things are off, but it's almost there:
The onsubmit handler is used at the form level. Either move the onsubmit to the <form> element or change it to an onclick event for the <input> element.
In order to reference the text fields the way you are, the <form> element also needs a name attribute. i.e. name="loginForm"
Do this:
Remove onsubmit from button add it to form.
Change id of form to name.
In the onsubmit of form append return false;.
Remove return false; from the if statements.
Change document.loginForm line to this:
document.forms['loginForm'].elements['username'].value //username/password depends.
Hope it works.
I have had the same problem as you before, and I solved it by changing the submit button to <input type="button" onclick="login();" />, and everything worked. However, the user then cannot submit the form with enter key (because there's no submit button in the form).

Controlling ENTER key

How can we make a form in a page doesn't submit on pressing Enter — rather. it does the same work as pressing a particular button or icon or image?
Here are the contents of my form:
<input type="text" id="txt" /><input type="button" value="search"
onclick="searchresult()" />
The problem is that if I press Enter, the form submits and text field clears itself but the function searchresult() doesn't show its effect. When only pressing the button, it works well.
HTML
<input type="text" id="txt"/>
<input type="button" value="search"/>
jQuery
$('input[type=text]').on('keyup', function(e) {
if(e.which == 13) { // 13 is keycode for enter
e.preventDefault();
}
})
You can also bind to submit() like following
$('form').submit(function(e) { // instead of only `form`,
// use with `id` or `class` combination
if(e.which == 13) {
e.preventDefault();
}
});
Remainder
Don't forget to place you code within
$(document).ready(function() {
// your code
});
in short
$(function() {
// your code
});
Alternatively, instead of disabling the enter key, you might be able to bind to the onsubmit event to perform any processing prior to submitting the form. From the MDN documentation:
The submit event is raised when the user clicks a submit button in a form ().
Try:
$('form').submit(function(event){
if(!$(':focus',this).is(':button'))
event.preventDefault();
});
This attaches to the form itself. If it was submitted any way other that clicking the submit button it halts the submission process. For better performance narrow down the 'form' selector.
Try this:
form
<form id="myForm">
<input type="text" id="txt" />
<input type="submit" value="search" />
</form>
js
<script>
$(document).ready(function(){
$("#myForm").submit(function(e){
e.preventDefault();
searchresult();
});
});
</script>

Categories

Resources