How to call the onclick function after pressing Enter - javascript

I am making a chat web application, to send a message, there's an input type="text" and an input type="button", using a function in JavaScript, I managed to work it out by adding onclick="sendMessage()" as an attribute for the input button, but I need to click on it, but I want it to work like any chat messengers or apps, the client writes something down and hits ENTER key, this could work if I used a <form onsubmit="sendMessage()"> and input type="submit" but then the page will refresh, How can I do this?

<form onsubmit="sendMessage();return false">
That prevents the default action of sending a request to the server.

This in-case you want also diable the enter button from Posting to server and execute the Js script.
<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
{document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();"/>

You'll have to hook into the onkeypress/up/down events for the textbox.
This should get you started:
Enter key press event in JavaScript

Use onkeydown() (or keyPress or keyUp, depending on semantics) instead of on click - this will get you an event with the event.keyCode you want - 13 - and you can easily submit using an AJAX request (i.e. XMLHttpRequest)
Simple Code: - raw Javascript, Don't need JQuery:
<html>
<script>
function keyPress(e)
{
if (!e) e = window.event; // needed for cross browser compatibility
alert(e.keyCode); // You want 13 here , so
// if (e.keyCode == 13)
// etc..
// return true; or false, if you want to cancel event
}
</script>
<body>
<input type="text" onkeydown="keyPress()" size="20"/>xx
</body>
</html>

Related

How to make firing "enter key" event in JavaScript?

I am working on something little app for sign-in automation.
It is like filling in the sign-in id, password inputs, and then pressing enter to submit.
I tried click(), submit() on the button element, but it's not working.
All I want is just fire the enter key event after filling the inputs, but many source codes are about get the keyboard event which I don't need to.
Is it impossible that press enter key event??
Try this code:
var element = document.getElementById(/* Element */);
element.addEventListener("keydown", fuction(e) {
if(e.key == "Enter") {
// Do something
}
});
You can use HTML form for this. Just wrap your inputs inside form and set onsubmit event. After you fill up the email and pass, enter will trigger the onsubmit.
Here is a simple example:
<form onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>
Hope this helps.

If the text-box value in HTML5 form is x, then y: Is that possible?

So basically, I want to enter a certain string into a text-box, and check what it is. It's basically for a command system that I'm trying to implement. There's a little Terminal pop-up and there is a text-box in it waiting for a command. This is the HTML I used to make the text-box inside a form:
<form id="command-input">
<input type="text" placeholder="Enter Command" id="command-box">
<input type="submit" style="display: none">
</form>
I made the submit invisible so you could press enter and it would submit the form. Here is the JavaScript I'm using:
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
I want to make it to where if I type "windows" into the command box and hit enter, it will change my stylesheet. The people on this website are smart, so I once again am asking for help. Thanks for contributing!
You will need to check with an event. Assuming this is in the plain tags; you can use the following:
var inputbox = document.getElementById('command-input');
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
inputbox.addEventListener('input', function (evt) {
if (this.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
});
Edit:
you can do this as well. Change the event to "onsubmit" if you want enter key to trigger.
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
document.getElementById('command-input').addEventListener(
'keyup',
function(eve){
if (eve.target.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
},
false
);
If you want to keep the changes even after the page refresh you might have to keep the file path in the localstorage and use that in dom load event.
Also, you really dont need to wrap this in a form tag. You can use a simple div and this is not triggered by a form submit.
You could create a function that you can call on form submission as explained here at https://www.w3schools.com/jsref/event_onsubmit.asp.
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input type="submit">
</form>
<script>
function myFunction() {
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
}
</script>

Why is my HTML form being submitted?

I have this form with 1 field. I want that when the user clicks or hits enter it should call a JavaScript function that will do validation and either display an error message or submit the form.
However, when hitting enter it submits the form regardless. (So far in my JavaScript validation function I only have alert ("Hello World"))
<form action="add-another-number-to-dnc.cshtml" method="post" id="addDNCform">
<h4>Enter 10-digit phone number without dashes, dots or parenthesis</h4>
<input type="text" name="pn" required placeholder="phone number"
title="Phone Number to Add to Do-Not-Call List"
onkeypress="if (event.keyCode == 13) document.getElementById('btnVldt').click()"/> <!-- all this is to treat [Enter] as a click -->
<input id="btnVldt" type="button" value="Add Number to Do Not Call list" onclick="submitDNC()"/>
</form>
I added all the page code in jsFiddle where you can test and verify that:
when clicking on the button, it correctly doesn't submit the form
when hitting enter it gives you an Error 404 which must mean, it's trying to load the page.
Added this:
Actually, if I use submit instead of button, it doesn't work also when clicking. However, in jsFiddle it seems to work.
Expanding on Praveen's answer here, I'm going to write the JavaScript "unobtrusively" to further separate function, presentation, and content:
HTML
<form action="add-another-number-to-dnc.cshtml" method="post" id="addDNCform">
<h4>Enter 10-digit phone number without dashes, dots or parenthesis</h4>
<input type="text" name="pn" required placeholder="phone number" title="Phone Number to Add to Do-Not-Call List" />
<button type='submit'>Add Number to Do Not Call list"</button>
</form>
(X)HTML5
Assuming that you want a 10-digit number in the box (numeric characters only), we can also use the pattern attribute on the <input> element in HTML5 as a form of validation for newer browsers (Firefox, Chrome, IE10, Opera):
<form action="add-another-number-to-dnc.cshtml" method="post" id="addDNCform">
<h4>Enter 10-digit phone number without dashes, dots or parenthesis</h4>
<input type="text" name="pn" required placeholder="phone number" title="Phone Number to Add to Do-Not-Call List" pattern="[0-9]{10}" />
<button type='submit'>Add Number to Do Not Call list"</button>
</form>
JavaScript (place inside <script> tags somewhere on the page)
function submitDNC(event) {
var valid = false;
alert('Hello world');
// your validation logic goes here, sets valid to TRUE if it's valid
if(!valid) {
event.preventDefault();
}
}
document.getElementById('addDNCform').addEventListener( 'submit', submitDNC, false );
No need to do any synthetic button clicking if all you're trying to do is validate upon form submission. Pretty soon with HTML5 we might not even need JavaScript for this, depending on what your validation logic is.
In your submitDNC() function, give a return false;.
function submitDNC()
{
alert("Hello World!");
return false;
}
Another thing is, change your input type from button to submit. Use:
<input id="btnVldt" type="submit"
value="Add Number to Do Not Call list" onclick="return submitDNC();" />
Explanation
The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.
Another Option
As Rink says, return false; is overkill for something that can and should be handled by preventDefault(). So, you can do this way, by using unobtrusive JavaScript.
function submitDNC()
{
alert("Hello World!");
var e = window.event;
e.preventDefault();
}
To prevent submit when pressing ENTER, use this piece of code:
function checkEnter(e){
e = e || event;
var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}
then, add the handler to the form:
document.querySelector('form').onkeypress = checkEnter;
I would change the to a Submit, although this isn't what's getting you in trouble here. For some odd reason browser programmers thought it was a good idea to code so that browsers assume buttons within forms submit them. You'll want to change onkeypress to call a function. In that function do something like this:
function keyPressPhone() {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
document.getElementById("addDNCform").submit();
return true;
}
else {
return false; // somehow prevents the form from being submitted
}
}

How do I submit a form to JavaScript without the submit button?

<form>
<input type="text" name="sometext">
<input type="button" value="Send" onClick="sendsometext(this.form);">
</form>
How would that be without using the submit button (I don't want it at all), just submitting the form by pressing the Enter key.
EDITED: I don't want to submit the form at all. I just want to type some text in the input field and call the function by the Enter key. Can I do this without JS?
<form>
<input type="text" name="sometext">
<input type="button" value="Send" onClick="this.form.submit">
</form>
Or, from the sendsometext function:
function sendsometext(form){
form.submit();
}
To run the function when the form submits (when the user presses Enter), try the following:
<form onsubmit="sendsometext(this)">
<input type="text" name="sometext">
</form>
If you return false from sendsometext, then the form will not submit.
Edit (Again)
Apparently you don't want to submit the form, all you want to do is let the function process the data and then do something with it. If your sendsometext function returns false, then the form should not submit:
function sendsometext(form){
//do something with the form;
return false;
}
and then the html code:
<form onsubmit="return sendsometext(this)">
<input type="text" name="sometext">
</form>
If this does not work, then please specify what browser you are using, and what happens. Also post a demo page with how you have implemented it. You cannot sumbmit the form to JavaScript without the use of JavaScript (that does not make sense).
Actually, I think you are looking for form.onsubmit
<form onSubmit="sendsometext(this.form);">
<input type="text" name="sometext">
<input type="submit" value="Send">
</form>
I wonder if the OP is missing the basic information that the browser automatically submits the form when you press Enter in any text field inside the form. That's why you can use the onsubmit handler if you want to invoke a method in response to the Enter key, per Marius' and Wogan's answers.
This is how you would create a Javascript function that acts on the the enter key being pressed to submit the form, instead of pressing the submit button.
Edit: On the code below where you see document.forms[0].submit() //submit the form ... You can change this line to point towards your function. That would stop the submission process and instead call your function when you press enter.
From http://jennifermadden.com/javascript/stringEnterKeyDetector.html
<input type="text" onKeyPress="checkEnter(event)">
function checkEnter(e){ //e is event object passed from function invocation
var characterCode;
if(e && e.which){ //if which property of event object is supported (NN4)
e = e
characterCode = e.which //character code is contained in NN4's which property
}
else{
e = event
characterCode = e.keyCode //character code is contained in IE's keyCode property
}
if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
document.forms[0].submit() //submit the form
return false
}
else{
return true
}
}

Prevent form redirect OR refresh on submit?

I've searched through a bunch of pages, but can't find my problem, so I had to make a post.
I have a form that has a submit button, and when submitted I want it to NOT refresh OR redirect. I just want jQuery to perform a function.
Here's the form:
<form id="contactForm">
<fieldset>
<label for="Name">Name</label>
<input id="contactName" type="text" />
</fieldset>
<fieldset>
<label for="Email">Email</label>
<input id="contactEmail" type="text" />
</fieldset>
<fieldset class="noHeight">
<textarea id="contactMessage" cols="20"></textarea>
<input id="contactSend" class="submit" type="submit" onclick="sendContactForm()" />
</fieldset>
</form>
<small id="messageSent">Your message has been sent.</small>
And here is the jQuery:
function sendContactForm(){
$("#messageSent").slideDown("slow");
setTimeout('$("#messageSent").slideUp();$("#contactForm").slideUp("slow")', 2000);
}
I've tried with and without an action element on the form, but don't know what I'm doing wrong. What has annoyed me more is that I have an example that does it perfectly:
Example Page
If you want to see my problem live, goto stormink.net (my site) and check out the sidebar where it says "Send me and email" and "RSS Subscription". Both are forms that I'm trying to get this to work on.
Just handle the form submission on the submit event, and return false:
$('#contactForm').submit(function () {
sendContactForm();
return false;
});
You don't need any more the onclick event on the submit button:
<input class="submit" type="submit" value="Send" />
Here:
function submitClick(e)
{
e.preventDefault();
$("#messageSent").slideDown("slow");
setTimeout('$("#messageSent").slideUp();
$("#contactForm").slideUp("slow")', 2000);
}
$(document).ready(function() {
$('#contactSend').click(submitClick);
});
Instead of using the onClick event, you'll use bind an 'click' event handler using jQuery to the submit button (or whatever button), which will take submitClick as a callback. We pass the event to the callback to call preventDefault, which is what will prevent the click from submitting the form.
In the opening tag of your form, set an action attribute like so:
<form id="contactForm" action="#">
It looks like you're missing a return false.
If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):
<input name="o" required="required" aria-required="true" type="text">
You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:
$('form').on('submit', function(event) {
event.preventDefault();
my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment
As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.
So if you want to get rid of these default pop-ups, use the click event on the submit button:
$('form input[type=submit]').on('click', function(event) {
event.preventDefault();
my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes
An alternative solution would be to not use form tag and handle click event on submit button through jquery. This way there wont be any page refresh but at the same time there is a downside that "enter" button for submission wont work and also on mobiles you wont get a go button( a style in some mobiles). So stick to use of form tag and use the accepted answer.
Unlike most of the previous answers, the solution that is described here demonstrates how to prevent a page from refreshing/redirecting on <form> submission using pure Javascript, instead of JQuery.
The HTML form
Below is the HTML <form>. There is no need to use the onclick event (which fires when the user uses the mouse to click on a button) or the onsubmit event (which fires when the user hits the enter key) on the submit button. These events are taken care of by the JS code described in the following section.
<form id="myForm">
<input type="text" name="contactName" id="contactName">
<input class="submit" type="submit" value="Submit">
</form>
The JavaScript code
Below is the JavaScript code to handle the <form> submission on the submit event. The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
Note: Make sure to register the event handler after the HTML element is added to the DOM tree (when loading the webpage); otherwise, a runtime error will be caused, as you'll be trying to set a property (an event handler) of a non-existent object. One way to ensure this is to simply place the script after the element in question (i.e., <form>), but as this might be a bit dangerous—since you are relying on how you assume a browser works—you can assign the event handler after the initial HTML document has been completely loaded and parsed, using the DOMContentLoaded event. Example:
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault() // Cancel the default action
sendContactForm();
});
});
All together
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault() // Cancel the default action
sendContactForm();
});
});
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="contactName" id="contactName">
<input class="submit" type="submit" value="Submit">
</form>
</body>
</html>

Categories

Resources