How to submit form with enter press in html textarea - javascript

I want to submit form as soon as I hit enter in the text area, this was working fine with input type text but, I don't know how to do it with text area. I have to use text area as I want text input to be expandable, how can I make it work? Thanks
<div ng-app="myApp" ng-controller="myCtrl">
<form ng-submit="sendMessage(newMessageContent)">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
<textarea id="typeMessageBox" placeholder="Write here and hit enter to send..." type="text submit" class="form-control-lg form-control" ng-model="newMessageContent"></textarea>
</form>
</div>

You can use ng-keypress and then check if keypress is equal enter then call to submit form function
On your textarea should be
<textarea ng-keypress="getkeys($event)" ng-model="newMessageContent"></textarea>
Then your angular code shold be
$scope.getkeys = function (event) {
if(event.keyCode == 13){
$scope.sendMessage( $scope.newMessageContent );
}
}

You can use the following jQuery code to submit your form when hitting Enter in your textarea:
$("#typeMessageBox").keypress(function (e) {
if (e.which === 13 && !e.shiftKey) {
e.preventDefault();
$(this).closest("form").submit();
}
});
That said, it may not be a good idea. If you want an expandable field, that surely is because you'll have several lines of text, therefore almost certainly a line break.
I would highly encourage you to add a helptext stating that you WILL submit the form when entering Enter, as your users would be very surprised by this behavior.
Even better: don't try to change native behaviors. A textarea is working like this for a good reason, and everybody is used to it. Changing its behavior may seem a good idea to you, but you'll probably loose your users.

Related

Can't Get Form to Submit Properly [duplicate]

The title speaks for itself... I have a couple of forms, one of them is just a single text input form and the other one is composed by two text inputs. I do not want any submit button in any of them, I want each form to submit whenever the user presses the ENTER button at any text input:
The form composed by just one input submits everytime the user presses the ENTER button - Perfect!
The second form composed by two text inputs does not behave this way, it does not submit when the user presses the ENTER button at any of both inputs.
Is there a way to make a form with more than one text input behave this way and avoid having a submit button in it?
Try adding this between the <form></form> tags
<input type="submit" style="display: none" />
Tested it and it works on Firefox and Chrome. If you have a submit input type in the form, enter should automatically submit it, regardless of whether it's visible or not.
I am actually using this myself in a login form, though in the username field, it makes more sense to move to the next field than to submit. Just in case you have a similar use case, here's the code I used (requires jQuery)
$('#username').keypress(function(event) {
if (event.keyCode == 13 || event.which == 13) {
$('#password').focus();
event.preventDefault();
}
});
Note that there is a slight bug though -- if the user selects a browser autocomplete username and presses enter, it still moves to the next field instead of selecting it. Didn't have time to debug this, but if someone can figure out how to fix it, that would be cool.
I was looking for a solution to this problem and want to share my solution, based on many posts over here. (Tested on modern Chrome/Firefox/IE)
So, using only Javascript the follow code submits the form if ENTER key is pressed on any field or if the button Submit is pressed. After that it clear/reset the form, which is a nice thing to do.
Hope it helps.
<!DOCTYPE html>
<html>
<body>
<p>Based on http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onsubmit</p>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<div onKeyPress="return myFunction(event)">
<form id="form01" action="demo_form.asp" onsubmit="return false;" >
Enter name: <input type="text" name="fname">
<input type="button" value="Submit" onclick="myFunction(0)">
</form>
</div>
<script>
function myFunction(e) {
if((e && e.keyCode == 13) || e == 0) {
alert("The form was submitted");
document.forms.form01.submit();
document.forms.form01.fname.value = ""; // could be form01.reset as well
}
}
</script>
</body>
</html>
Be sure that your inputs are inside "form" element and give the "form" element an "action" attribute.
You will have to look for the Enter key press. This post here shows how to do that.
Enter key press event in JavaScript
You can use the code below to submit a form after pressing Enter.
<input id="videoid" placeholder="Enter the video ID">
<button id="mybutton" type="button" onclick="myFunction()">Submit</button>
<script>
var input = document.getElementById("videoid");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("mybutton").click();
}
});
</script>

Textarea strange behavior inside a form

My issue is quite simple.
I am not able to put new lines / press enter to put a new line inside if the textarea is inside a form.
Works great outside the form. I NEED the form and I cannot remove it. The textarea must be inside the form
Is there a way to fix this? Why this happens?
<form>
<textarea></textarea>
</form>
Not enough information, it just works that way, I think you should share the CSS applied on both elements.
Make sure the text area is focused when pressing Enter otherwise it should submit
Here is a minimal example. In my browser (Chome) I can press enter while inside the text-area, without the form being submitted. Does that work for you too? Then there is something else with your code that causes the form to be submitted.
myForm.addEventListener("submit",event=>{
event.preventDefault();
console.log("Form submit", Date.now());
});
input[type=text],
textarea{
width:100%;
}
<form id="myForm">
<textarea>Enter you text here. You should be able to press enter here to create a new line, without the form being submitted.</textarea><br>
<input type="text" value="Pressing enter here will submit the form"><br>
<input type="submit">
</form>

Submitting a form on 'Enter' with jQuery only fires ONCE

I've been racking my brain on this for a couple days. I've looked thru many different solutions, but I can't figure this out.
I have a simple form in a PHP page with a text box and search button that once the search is performed, the entered text is highlighted on the document.
PROBLEM: After entering a search term in the text box and CLICKing search, all is well. However, when I PRESS enter to search, it only fires ONCE. Clicking search will continue to work with no issues.
What am I doing wrong here?
$('document').ready(function() {
$('#button').click(function() {
var search = $('#text-search').val();
});
$('#text-search').keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) { //Enter key pressed
$('#button').on(); //Trigger search button click event
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search" class="Column">
<input name="text-search" id="text-search" type="text" size="20" maxlength="30" placeholder="search & highlight">
<input name="searchit" id="button" type="button" value="Search" onClick="highlight()">
</div>
HTML:
You're doing it a bit wrong and you're putting too much overhead to your code. You can achieve the same without all these keypress events. The submit event will suffice and it works flawlessly with Enter as well! However, you need to wrap your inputs with form element and change input type from button to submit:
var searchbox = document.querySelector('#text-search')
var searchForm = document.querySelector('#search')
searchForm.addEventListener('submit', function(e) {
e.preventDefault()
highlight(searchbox.value)
searchForm.reset()
})
function highlight(value) {
// do something with your value
alert(value)
}
<form id="search" class="Column">
<input name="text-search" id="text-search" type="text" size="20" maxlength="30" placeholder="search & highlight" />
<input name="searchit" id="button" type="submit" value="Search" />
</form>
Always try to use form element if you are getting user input. This gives you better control over input fields. Also it's semantically better than lonely inputs here and there.
Try to avoid inline javascript in your HTML. It's just a bad practice.

Accidental JavaScript redirct?

I have a form that adds an item to a list when I press enter or hit a submit button. I'm not sure what I've changed, but suddenly pressing enter seems to redirect the URL, while clicking the button acts normally.
The HTML portion looks like this:
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
</form>
The jQuery is:
$('#check').click(function () {
addIngredient('new-ingredient');
});
$('.new-ingredient').keypress(function (e) {
if (e.keyCode == 13) {
addIngredient('new-ingredient');
}
});
So it's running the same function either way. In both cases, it successfully adds the ingredient to the list, but in the 2nd case, the page is redirected from "recipe.html" to "recipe.html?new-ingredient=".
And here's the part that really confuses me: when I add an extra input to the form, this problem doesn't occur when I press enter in either box:
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
<input type="text"></input>
</form>
Also, if I add in an actual button (not my clickable image), it redirects like pressing enter, even though I have no code to do anything if the button is pressed. In this case, the extra input field has no effect.
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
<button id="button">Add Ingredient</button>
</form>
I have absolutely no idea why this is happening. Even if I get rid of the jQuery to perform an action when I hit enter, this still happens. I'm new to JavaScript, so sorry if this is something obvious, but I'd really appreciate some help.
I can also provide more of my code if it's relevant, but I didn't want to clog things up with a ton of code.
Hitting enter (or clicking the button if its there) is submitting the form (this makes it appear to "redirect the URL"). You need to prevent that from happening with e.preventDefault(). So in the click listener:
$('#button').click(function(e){
e.preventDefault();
addIngredient('new-ingredient');
});
Put that in each of the listeners, or get rid of your form tags so there isn't anything to submit (as was mentioned in the comments).
I don't entirely blame you for being confused. The browser default behavior is to perform the "submit" action, whatever it is, when someone presses enter while a field in the form is highlighted. As elclanrs said, you can override the submit action; in fact, I'm pretty sure in JQuery it's just this:
$('#add-ingr').submit(function(e) {
if ('event is not coming from button')...{
e.preventDefault();
}
});
I'm afraid I couldn't explain why adding a blank input changed the effect, though. Through my laziness, I have also left you the work of determining the best way of allowing actual submissions, though (if the form gets submitted to the server, you won't want to block submit every time)

HTML capture enter key and tab key

I want to prevent the enter key from submitting the form, I want it to act as a TAB key to just jump to the next field in the form or the next element.
Is this possible in HTML/JS?
if not possible to make the enter button act as a tab, is there a way to prevent the submission of the form and make only the form be submitted using the buttons on the HTML??
EDIT:
I have received a solution to this problem when I was asking for another problem!
here you can find the solution.
For accessibility/usability reasons, you really shouldn't prevent the Enter key from submitting the form (assuming the browser was going to do that anyway; IIRC, some older browsers didn't).
Assuming that you want to do this because the submit button has a click handler you'd like to happen for every form submission, you should instead move that code into a separate function and invoke it from a the form's submit event.
In jQuery, it would look something like:
$('#myForm').submit(function(e) {
if (!isValid()) {
e.preventDefault(); // Could also be `return false;` but I prefer preventDefault.
}
});
See the docs.
FYI, if you're trying to do some validation, you should check out the validation plugin.
<html>
<body>
<script>
function tmpFn(val){
if(event.keyCode=='13'){
if (val<4)
document.forms["yourform"].elements["box" + (val+1)].focus();
else
document.yourform.submit();
return false;
}
return true;
}
</script>
<body>
<form name="yourform" action="#">
<input type="text" name="box1" onkeypress="return tmpFn(1)"><br>
<input type="text" name="box2" onkeypress="return tmpFn(2)"><br>
<input type="text" name="box3" onkeypress="return tmpFn(3)"><br>
<input type="text" name="box4" onkeypress="return tmpFn(4)"><br>
<input type="submit" name="done" value="Submit">
</form>
</body>
</html>
EDIT: Refrain from using 'eval'.. Thanks Tim and Andy!
It might be possible to solve this using some jQuery - although I don't know how to imitate a keypress.
$(document).keyup(function(e) {
if(e.keyCode == 13)
{
//Code to imitate keypress of Tab key
}
});
Edit: Made a quick jsFiddle to "imitate" tab presses, which would go to the next field like you mentioned. (This one works based on the Enter key being pressed in a field)
jsFiddle
Off the top of my head, to prevent the enter button from submitting the form, don't use a submit button, rather use a <input type="button" ... onclick="submitForm();"> to call javascript to submit the form. I could be wrong, but I believe this should prevent pressing enter on any other element submitting the form.

Categories