How to trigger an event when use enter key for html - javascript

I want to send message when I use the enter key but it not working
for my html
<form id="form">
<textarea type="text"></textarea>
<input type="submit" value="Send">
</form>
for my js
const sub = document.getElementById('form');
// send message when hit
sub.addEventListener('submit', send);
// use enter to send message
sub.addEventListener("keypress", (event)=> {
if (event.keyCode === 13) {
send();
}
});
function send(event) {
Also, I keep getting 'keyCode' is deprecated this error message
This is not working, someone help? Thank you in advance!

I have made adjustment to your code and added the event.preventDefault(). The PreventDefault() is used to prevent the default action belonging to that even from happening.
I Have also used the event.which to get the keycode of the enter key
const sub = document.getElementById('form');
// send message when hit
sub.addEventListener('submit', send);
// use enter to send message
sub.addEventListener("keypress", (event)=> {
if (event.which === 13 ) {
//this will prevent the normal behavior of going to a new line when the enter button is pressed
e.preventDefault()
send();
}
});

Related

Uncaught TypeError: myFormRef.submit is not a function, I tried to make my textarea in React submit the value with the key Enter

I tried to make my textarea input in React submit the value with the key Enter, but I got this error and I don't know why this is happend:
Error Message
This is my function to catch the key:
const myFormRef = useRef();
const onEnterPress = (e) => {
if(e.keyCode == 13 && e.shiftKey == false) {
e.preventDefault();
console.log(myFormRef.submit());
}
}
This one is the Form with textarea:
<Form id="myForm" ref={myFormRef} onSubmit={sendMessege}>
<TextareaAutosize
className='text_input'
placeholder='Digite algo aqui'
type="text"
value={formValue}
onChange={(e) => setFormValue(e.target.value)}
disabled={!user}
minRows={3}
maxRows={6}
onKeyDown={onEnterPress}
/>
</Form>
Someone can help me?
You need to get the current from the reference.
Please try:
console.log(myFormRef?.current?.submit());

Building real time commenting feature

I am trying to add real time comment feature to all posts user timeline page.
Here is what i have done:
All Posts contain comment section having following html form:
<form action="#" class='post-comment' data-id='3214'>
<input type="text" name='comment'>
<input type='submit' style='visibility: hidden;'>
</form>
Here is my Javascript code which handles the form submit event:
$(".post-comment").on('submit', function(e){
e.preventDefault(); //STOP default action
var id = $(this).attr("data-id");
console.log('Comment on: '+id);
var dbref = firebase.database().ref('post-user/'+id+'/comments');
var data = $(this).serialize();
var t = Date.now();
dbref.push().set({
postedAt: t,
text:data.comment,
pid:id
});
})
After making some input as comment when user presses the enter key then the web page reloads instead of invoking function in Javascript.
I want to get comment data and corresponding post details(id,authorid) and send comment data to firebase on enter key press.
After doing some searches i came to know about key press events as below:
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("form").submit();
}
});
But in this case i have multiple forms that is every post contains corresponding comment form so i am confused how to implement this here.
Any help will be appreciated.
Give your form an id:
<form id='comment-form' action="#" class='post-comment' data-id='3214'>
Then submit just that form:
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("#comment-form").submit();
}
});

HTML Form: How to remember text values of button click?

If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!
Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-

Enable Dialogbox only when data submited in a form through submit button

I am trying to save a data with next button.After entering the form when I click next button a popup dialogbox will open asking "Whether you wanna submit ur data?"
So for this What I did
In submit button I have this code :
<?php echo $this->Form->submit('Next', array('class' => 'btn btn-primary','id'=>'movesubmitbtn'));?>
Its Cakephhp submit button
and here is my javascript code :
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
// Interrupt the submit function
$('#movesubmitbtn').click(function(){
if(confirm('This is your final submission of the data. Do you want to continue?')) {
return true;
}
else {
return false;
}
});
movesubmitbtn
});
</script>
Please help me out,how to add disable property so that I will get the popuponly when data is present.
Try this:
<button id="submitBtn" type="submit" disabled="disabled">Submit</button>
<textarea id="textBox" rows="10" onblur="if(this.value == ''){document.getElementById('submitBtn').disabled = true;} else {document.getElementById('submitBtn').disabled = false;}"></textarea>
Or simpler:
<button id="submitBtn" type="submit" disabled="disabled">Submit</button>
<textarea id="textBox" rows="10" onblur="document.getElementById('submitBtn').disabled = (this.value == '');"></textarea>
Using jQuery;
$('form').on('change', function(){
// this will be triggered with every 'change' inside the form
// e.g. Every time the user modifies a input
// check if all (required) inputs contain a value
if('' == $('#inputA').val() || '' == $('#inputB').val()){
$('#movesubmitbtn').disabled = true;
} else {
$('#movesubmitbtn').disabled = false;
}
});
Also consider putting the code you're using on the 'submit' event of the form instead of on the 'click' of the button. This will prevent the form being submitted if the users presses the 'enter' key inside a text field.

Pressing 'enter' on a input type="text", how?

I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code :
(...)
<script type="text/javascript">
// Autocomplete suggestions
$(function () {
$("#autoCompInput").autocomplete({
source: "/Suggestions",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autoCompInput").val(ui.item.value);
$("form").submit();
}
}
});
});
// Provide search results
$(function () {
$("#autoCompSearch").click(function () {
var searchParameters = $("#autoCompInput").val();
var jsonData = JSON.stringify(searchParameters, null, 2);
window.location = "/Search?criteria=" + searchParameters;
});
});
</script>
(...)
<input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "#ViewBag.SearchInfo"/>
<a id= "autoCompSearch" href = "#" ><img src="#Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a>
(...)
With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me?
Thank you,
You should bind the keypress event to your input
$("#autoCompInput").bind("keypress", {}, keypressInBox);
function keypressInBox(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
e.preventDefault();
$("yourFormId").submit();
}
};
With similar HTML:
<input type="text" id="myTxt" />
<input type="submit" id="mySubmit" />
This script (which uses the latest jQuery 1.7.2) should do it:
$('#mySubmit').click(function() {
alert('Submitted!');
return false;
});
$('#myTxt').on('keyup', function(e) {
if (e.keyCode === 13) {
$('#mySubmit').click();
}
});
Here's a working example.
To assign a keyup event in jquery
$("#autoCompInput").keyup(function(event) {
if (event.keyCode==13) {
alert('enter key');
}
});
I think there is a better and more standard solution to this type of problem.
you can have a GET form around those inputs and whenever you press enter on any input inside that form, it will be submitted to whatever is in the action attribute of the form. This is how it would look like (I took your code but I am removing the bits irrelevant for my answer):
<form id="idForJqueryOnly" action="/Search" method="GET">
<input type="text" name="criteria" value="someuserinput"/>
<button type="submit"><img src="...")" alt="Search" /></button>
</form>
This is standard browser behaviour. So, what the form does? when submitted the browser creates a URL like this:
http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinput
What happened is that the browser took all the inputs with name and value (and not disabled) from the form and serialized them into url form.
Now, the submit event can be triggered by pressing enter on any of the inputs inside, including buttons as long as the buttons don't have the attribute type="button".
If you wanted to do more things with the data with javascript before going to the search page, you can do this with jquery:
$("#idForJqueryOnly").submit(function(){
// here you can do stuff like serialize the form, or sanitize the input of tue user.
var data = $("#idForJqueryOnly").serialize();
$("[name=criteria]").val($("[name=criteria]").val().customSanitizeMethod());
// if you return false, the form will not submit, say, for validation errors:
return customValidator.isFormValid("#idForJqueryOnly");
})

Categories