Two Events Fired when I press enter key - javascript

In my code, I have the following javascript code block in the header section
function validateForm(bid) {
switch (bid) {
case "submitIDSearch":
alert("submitIDSearch");
return false;
case "submitNameSearch":
alert("submitNameSearch");
return false;
}
}
function fKeyDown(e) {
var kc = window.event ? window.event.keyCode : e.which;
if (kc == 13) {
document.getElementById('submitNameSearch').click();
}
}
Then I have the following HTML code block
<form name="checkAbsenceForm" method="post" action="absenceReport.htm" onsubmit="return validateForm(this.submited)">
<label class="q">ID * <input id="searchRUID" name="searchID" maxlength="9" /></label>
<input id="submitIDSearch" type="submit" value="Search ID" onclick="this.form.submited = this.id;" />
<hr />
<label class="q">First Name <input id="searchFirstName" name="searchFirstName" maxlength="23" onKeyDown="javascript:fKeyDown(event);"/></label>
<br />
<label class="q">Last Name * <input id="searchLastName" name="searchLastName" maxlength="23" onKeyDown="javascript:fKeyDown(event);" /></label>
<input id="submitNameSearch" type="submit" value="Search Name" onclick="this.form.submited = this.id;" />
</form>
What happened was that when I press Enter key in the searchLastName input text box, both alert message box pops up. One showing submitNameSearch and the other showing submitIDSearch. submitNameSearch is the desired event, but submitIDSearch is not, I think it is somehow triggered by default.
May I ask if there's a way to get rid of the submitIDSearch event when I press Enter key in the searchLastName input text box?
Thanks a lot!

When you press Enter in a form, the form is submitted. That's the reason of the second call to validateForm.
Two solutions :
1) Remove the onKeyDown="javascript:fKeyDown(event);" to have the normal validation defined on onsubmit=... apply.
2) In fKeyDown, add e.preventDefault(); to prevent the default handling of the key event :
function fKeyDown(e) {
var kc = window.event ? window.event.keyCode : e.which;
if (kc == 13) {
document.getElementById('submitNameSearch').click();
e.preventDefault();
}
}
But if you really do just this in fKeyDown, solution 1 is enough.

Related

how to trigger a function by pressing enter?

I have this button that leads to a method in javascript that filters the information of a table:
<button type="button" id="search" title="Buscar" onclick="fn_cliente.filtraInformacion();"></button>
There are several fields for which you can filter the information, I want that when pressing "enter" on any input, it executes the same method as when clicking on the button
Use the following to bind the enter event to your search fields.
document.querySelectorAll('.searchfield').forEach(function(input) {
input.addEventListener('keypress', function(e) {
if (e.keyCode === 13) filtraInformacion();
});
});
Look at this code snippet
function filtraInformacion() {
console.log('filtraInformacion has been called!');
}
document.querySelectorAll('.searchfield').forEach(function(input) {
input.addEventListener('keypress', function(e) {
if (e.keyCode === 13) filtraInformacion();
});
});
<button type="button" id="search" title="Buscar" onclick="filtraInformacion();">Click me</button>
<br>
<input id='name' class='searchfield' placeholder='Press Enter!'>
<br>
<input id='lastname' class='searchfield' placeholder='Press Enter!'><br>
<input id='gender' class='searchfield' placeholder='Press Enter!'>
See? when the enter key is pressed, the function filtraInformacion is called.
This works. You can adapt it to whatever element you want.
<input type="text" id="account-location-country-input" class="mdc-text-field__input" required onkeyup = "if (event.keyCode == 13)document.getElementById('edit-account-button').click()">

Enter key doesn't activate button

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();
});
});

How to limit enter key press to only one button in a form having two submit buttons

I have an HTML form having two submit type input buttons with different actions attached. The form should get submitted on click of any of these buttons. But on enter key press, button-B should trigger the submit. Now as i have button-A on top of button-B in the order, button-A is getting triggered on enter press.
Please note that changing the order of buttons is not possible in my case.
My code goes like this,
<form method="POST" action="someAction">
<input type="text" name="fName"/>
<input type="text" name="lName"/>
<input type="submit" value="Action-A" name="button-A"/>
<input type="submit" value="Action-B" name="button-B"/>
</form>
You can add listeners to all inputs and when the user hit enter you can prevent the default action by using e.preventDefault(). Then select the second submit button and click it.
<script>
window.onload = function() {
//Select all of input in #form1 of type text
var inputs = document.querySelectorAll("#form1 > input[type=text]");
for(var i = 0; i < inputs.length; i++) {
//Add listeners
inputs[i].addEventListener("keypress", function(e) {
var key = e.which || e.keyCode;
//Check if enter is pressed
if(key == 13) {
//Prevent from submitting with A
e.preventDefault();
//Click B
document.getElementById('b').click();
}
}, false);
}
}
</script>
<form id="form1" method="POST" action="someAction">
<input type="text" name="fName"/>
<input type="text" name="lName"/>
<input type="submit" value="Action-A" name="button-A"/>
<input type="submit" value="Action-B" id="b" name="button-B"/>
</form>

How can I print users input to screen on when they hit return in HTML

I have several text boxes that users will be filling out. They will enter something into one then hit the 'return' key. Once they hit the return key I need to display the data they entered into the text box underneath it. This has to be done on a single webpage, and I cannot figure it out. I cannot use HTML5 'output' tag because this has to work with Internet Explorer.
<input name="idStn1" type="text" />
Here is another example, more close to what you originally requested.
jsFiddle demo
HTML:
<div>Type some text in the fields below and press Enter key</div>
First Name: <input id="fname" class="dataentry" type="text" /><span></span>
Last Name: <input id="lname" class="dataentry" type="text" /><br />
<input id="fname_text" type="text" disabled="disabled" /><span></span>
<input id="lname_text" type="text" disabled="disabled" />
javascript/jQuery:
var thisid, theval, currInput;
var textboxes = $("input.dataentry");
$("input:text").on("keydown", function(event) {
// track enter key
var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
if (keycode == 13) { // keycode for enter key
//get val of current input and stick into paired view-only field
theval = $(this).val();
thisid = $(this).attr('id');
$('#' +thisid+ '_text').val(theval);
//select the next input box
currInput = textboxes.index(this);
textboxes[currInput+1].focus();
return false;
} else {
return true;
}
}); // end of function
The following code will allow you to click a button by pressing Enter key within a specified input field:
jsFiddle demo
HTML:
First Name: <input id="fname" type="text" /><br />
Last Name: <input id="lname" type="text" /><br />
Age: <input id="myAge" type="text" /><br />
Email: <input id="emailadd" type="text" /><br />
<input type="button" id="mybutt" value="Go" />
javascript/jQuery:
<script type="text/javascript">
$(document).ready(function() {
$("#emailadd").on("keydown", function(event) {
// track enter key
var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
if (keycode == 13) { // keycode for enter key
// force the 'Enter Key' to implicitly click the #mybutt button
$('#mybutt').click();
return false;
} else {
return true;
}
}); //END #emailadd.click
$('#mybutt').click(function() {
alert( 'Hey, you clicked mybutt' );
});
}); //END document.ready()
</script>
This code uses the jQuery javascript library, so you must reference this library (usually in the head tags of the document), thus:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

How make enter button (keyboard) work properly in forms in IE8?

The problem is only happening in Internet Explorer. In any other browser I can submit the form by hitting enter on my keyboard, in IE8 I have to actually click the button.
I searched around for fixes for a while and found a few things but it's still not working. The javascript I'm using should be looking for keycode 13, which is enter, but when I hit enter the field clears itself without submitting the form and the keycode is not triggered. The keycode thing only returns results for letters and not for shift/enter.
Here's the HTML my current solution:
<form action="chatscreen.php" name="loginform" method="post">
<p>Please enter your name to continue:</p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" onkeyup="whichButton("loginform","enter")"/>
<button type="submit" name="enter" id="enter" value="Enter">Button</button>
</form>
And here's the javascript I tried to implement as a fix:
<script type="text/javascript">
function whichButton(formname,elementname) {
alert("got a key = " + event.keyCode);
if (event.keyCode === 13) {
var followingInput = document.getElementById(elementname);
document.formname.elementname.click();
}
}
</script>
<script type="text/javascript">
function whichButton(formname,elementname) {
var keyID = (window.event) ? event.keyCode : keyEvent.keyCode;
if (keyID === 13) {
var followingInput = document.getElementById(elementname);
document.formname.elementname.click();
}
}
</script>
Simple; just set your defaultbutton property
<form id="Form1" defaultbutton="enter" action="chatscreen.php" name="loginform" method="post">
Hope that helps :)

Categories

Resources