Map enter key to submit while not inside input - javascript

I have a form with multiple input boxes that I'm trying to get to submit when I press the enter key, regardless of whether or not one of the inputs is currently highlighted. That is, I want to be able to enter text, click the background of the page, hit enter, and have the form submitted. I have tried making a hidden button, but this solution only appears to submit when the cursor is inside one of the inputs.

Use onkeypress on document using pure javascript:
Fiddle.(demo)
JS:
var form = document.getElementById('form');
document.onkeypress = function(e) {
if(e.keyCode === 13) //if enter pressed
{
form.submit();
}
}
Here's another solution using addEventListener, as suggested by Matt:
var form = document.getElementById('form');
function submitForm(e) {
if(e.keyCode === 13) //if enter pressed
{
form.submit();
}
}
document.addEventListener('keypress', function() {submitForm(event)}, false);
As a side note:
I would discourage you using jQuery on places where pure JS can help you easily that's why gave you a javascript solution. I would discourage that because jQuery increases the load on the server alot!
As you said you are new to javascript do the following steps to get your script running everytime:
Add my code to a file with .js extension
Add <script src="your_filename.js" type="text/javascript"></script> before your closing </body> tag.
Refresh your page and voila.

With the help of jQuery:
$(document).keydown(function(e) {
if (e.keyCode == 13) {
$('#your-form').submit();
return false;
}
});

Related

How to separate the "press-key" from the "click-mouse" event to prevent submission when press-key?

I have the "chips" form link you can see in the attached image here and I want to create a condition such as if someone press "Enter" he can note the item added but what happens here is that form sends the data to backend.
I tried many times to modify the behavior using the "event" but it didn't work you can see the approaches I sticked with:
Approach1:
// input to submit job
const submit_job = document.getElementById("submit-job");
submit_job.onclick = (e) => {
e.preventDefault();
if (e.key !== "") {
console.log(e.currentTarget)
} else if (e.pointerType === "mouse") {
submit_job.onsubmit = () => {
return true
}
}
}
// This approach won't work because I found that "e.key" worked only when typing by Keyboard
Approach 2:
function getEventType(event) {
if (event.type === "keydown") {
event.preventDefault();
}
}
submit_job.addEventListener('keydown', getEventType, true);
submit_job.addEventListener('click', getEventType);
so, any help in that issue, please?
Note:
No need to see the full code because the code is working fine but when I place it into the form this problem occurs so, you can spire me using that variable only "submit_job" in your answer.
Your implementation of the form submission does not seem like a good idea. You should not prevent users from submitting the from when pressing "Enter". Clicking "Enter" should trigger a form submission which is common for most forms. Why not add a unique button beside the input field that when clicked allows the user to enter a note or text? If you take your current approach users will only be able to submit by clicking the submit button which is bad practice. I suggest creating an additional button and adding an event handler to that button so you have a button that adds notes when clicked, so pressing "Enter" will not clash with what you are trying to accomplish.

EventListener for submit form irrespective of form id in JavaScript

Is there any way to add an eventlistener that will run whenever any of the forms in the webpage gets submitted? This need to run on all the websites, for example, on www.google.com, whenever the user searches something, the eventlistener should run.
I am not using any html file. So it is not possible to use the form id.
I am a Swift developer but need to use JavaScript in this scenario. So really need some help here.
Note: There is a similar question on StackOverflow, but that is for Ajax. I am looking to use only JavaScript.
UPDATE: I need an eventlistener that will get executed whenever a user searches something on any search engine website, like google, bing, etc. The eventlistener should run when the users 1. hits enter on the search box. 2. clicks on the search button. 3. clicks on or hits enter on the autocomplete search predictions.
as of now I am able to achieve 1 and 2 using the following code:
document.body.addEventListener('keypress', function(e) {
// check if the element is an `input` element and the key is `enter`
if((e.target.nodeName === "INPUT") && e.key === 'Enter') {
console.log('Enter pressed Input');
}
});
document.body.addEventListener('click', function(e) {
if(e.target.nodeName === "INPUT") {
console.log('Clicked Input');
}
});
document.body.addEventListener('keypress', function(e) {
if(e.target.nodeName === "DIV" && e.key === 'Enter') {
console.log('Enter pressed in Autocomplete');
}
});
document.body.addEventListener('click', function(e) {
if(e.target.nodeName === "LI") {
console.log('Clicked Autocomplete');
}
});
However, I am not able to achieve target 3 yet.
I thought maybe if I was able to implement an eventlistener that would run whenever the form gets submitted, all the three targets will be achieved. I am not sure as I am new to JavaScript.
I also need to do it without using any form id as the same code needs to be compatible with multiple forms.
I hope this makes it clearer now.
Well then you don't need to listen for the key press, instead listen for the submit event, using event delegation, here is a solution, note that we're getting the value of the input with the name "q" cause most of the search engines use it as a name for the search input:
document.body.addEventListener("submit", function(e) {
// prevent the form submitting
e.preventDefault();
// clear the console from old messages
console.clear();
// output the serached text
console.log(e.target.querySelector("[name='q']").value);
// after 3 seconds submit the form (just for demonstration)
setTimeout(function() {
e.target.submit();
}, 3000);
});
<form action="https://duckduckgo.com/">
<input type="text" name="q">
<input type="submit">
</form>

Jquery: Enter to blur

Please check out this fiddle: http://jsfiddle.net/7wp9rs2s/ this is how far I have come with this project.
Basically, in the above fiddle you can double click on one of the 4 items and when you do, you get a textbox where you can edit it. Then you click out and it goes back to being a text. Most users wont click out but will instead press enter (like SO's comment function) so if the user presses enter, while making the edit, I want the script to react in the same way as if the user clicked out of the box.
I know how to capture the Enter key:
$(document).keypress(function(e) {
if(e.which == 13) {
alert("in Enter");
}
});
But I do not know how to make the function do what I need :(
Your functions are called on blur, so simply trigger a blur on the input :
$(document).keypress(function(e) {
if(e.which == 13) {
$(e.target).blur();
}
});
Fiddle

Simulating a click to submit a form in jQuery

Alright so I have a text field that will have a bar code scanned into said text field. It will search the database and return information in the form of a submit button. I am using this code to simulate a click on the submit button.
if($.browser.msie){
//simulate a click on the button
$("#search").keyup(function (e) {
if(e.keyCode == 13) {
$('input:submit').click();
}
});
}
The problem with this code is that it takes all of the keystrokes and then clicks the button that many times. This submit will represent data that gets written into the database, so if the bar code was abc123 it would do this action 6 times, but I just need it to do it once. How do I fix this? My code works in FF and Chrome, but not IE, which is the one I need to get this to work in. Grrr I hate IE so much!
Why do you need to "click" that submit button? Why don't you just submit the form like:
$("#search").blur(function(){
document.myform.submit();
});
Your barcode reader will do this for you.
Try to get code like this:
var keyCode = (window.event) ? e.which : e.keyCode;

JQuery Event for when user presses enter?

What's the simplest way to have a function called whenever the user hits enter after typing in a textbox?
You'll need to listen for the keypress event. It's probably easiest to do this with delegate:
$(document.body).delegate('input:text', 'keypress', function(e) {
if (e.which === 13) { // if is enter
e.preventDefault(); // don't submit form
// do what you want here
}
});
<textarea id="text"></textarea>
$('#text').keydown(function(e){
if (e.keyCode == 13) {
alert('Enter was pressed.');
}
});
http://jsfiddle.net/dNfC2/
HTML code
<input type="text" id="txt"/>
<input type="button" id="btn" value="send"/>
jquery code
$("#txt").keydown(function(event){
if(event.keyCode == 13){
alert("enter button pressed");
$("#btn").click();
}
});
Running example here : http://jsfiddle.net/Xamkp/5/
try this:
jQuery(document).bind('keydown', 'return',function (){ /*do something*/ });
you will need a plugin:
jquery.hotkeys
Well it's rather simple to do in the form you asked:
$('#idOfTextBox').keyup(function(event){
// enter key pressed
if(event.keyCode=='13')yourFunction();
});
Take note this will still append the enter key to the box. You might wanna try keydown or keypressed if you don't want that.
Be sure to check keyUp() for more detail.
Put the <input> in a form, and write a handler for the form's submit event.
This way you're not explicitly looking for any particular key; you're just waiting for the form to be submitted normally. And in every mainstream browser, pressing enter while filling out a form will submit the form.
Note that you do not need to have a physical submit button on the screen if you don't want (in which case the enter key will likely be the only way to submit the form).

Categories