I need to know how to send a message in my textarea using enter, not only with the submit button.
This is my code.
function onSend () {
const textareaValue = $textarea.value;
if (textareaValue !== '') {
const template = `<div class="conversation-active">
<img src="Foto1.png" alt="Avatar">
<div class="box-message">
<p class="name">Michael Alean</p>
<span class="time-message">${timeNow}</span>
<div class="message">
<p>${textareaValue}</p>
</div>
</div>`;
$chat.innerHTML += template;
$textarea.value = '';
}
}
you can use like this:
firstly declare named pressed function.
this function checks whether the enter key is pressed. if pressed to the enter key will be manually trigger to onSend function.
function pressed(e) {
// Has the enter key been pressed?
if ( (window.event ? event.keyCode : e.which) == 13) {
// If it has been so, manually trigger onSend function
onSend();
}
}
Secondly you should add to textarea props the this code
onkeydown="pressed(event)"
like this:
<textarea name="myTextArea" onkeydown="pressed(event)"></textarea>
The enter key creates linefeeds (LFs) in a textarea so I suspect you're using the wrong type of input field.
Normally, for input type=”text” or input type=”url” you can use the event...
onchange="alert('OK');"
Which does fire when you press the enter key but not in a textarea.
Forcing a textarea to fire with the enter key; although not impossible, is pretty stupid and a sign that you are using the wrong field type.
Related
In my php file I have the following:
<a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='. $_GET['page'] .'&record=' . $record_number . '"">' . $record_number . '</a>
This sends a user somewhere based on the current page value and record value, it is framed in a pagination type situation, so it goes to the next record, it works, its fine.
I also have a text input box, the idea is that a user can type a number and press enter and if that record exists the user goes to that record. If for instance the user chooses record 23, the code would be like this:
<a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='. $_GET['page'] .'&record=23"">23</a>
So far so good, obviously I'll add in an if ($record_number >= $max_record) for good measure.
Now the question, I would like the users to be able to enter a value into an input box, press enter and follow the hyperlink, how is this achieved?
<input type="text" style="width:200px;" class="form-control float" id="defaultFormControlInput" placeholder="Go to record" aria-describedby="defaultFormControlHelp">
--- UPDATE ---
The below is the 'enter' function so the event listener knows when the enter key is pressed. Given #imvain2's answer below a 'Go' hyper link is displayed and when the link is clicked it functions as required. However, I would like to bypass the link creation so that when 'enter' is pressed then the link is followed without the need for creating a hyperlink first.
document.querySelector('#input').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
let url = "?page=artefact&record=" + e.target.value;
goLINK.classList.toggle("active");
goLINK.href = url;
}
});
You can use javascript.
I'm using URLSearchParams to get the query string parameter for page. Then in an keyup event I'm looking for the enter button and putting together the URL and adding it an anchor and displaying that anchor by toggling a class called active
let input = document.querySelector("#defaultFormControlInput");
let goLINK = document.querySelector(".goLINK");
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
input.addEventListener("keyup",function(e){
if(e.keyCode == 13){
let url = "?page=" + (params.page || "1") + "&record=" + e.target.value;
goLINK.classList.toggle("active");
goLINK.href = url;
}
});
.goLINK{display:none;}
.goLINK.active{display:block;}
<input type="text" style="width:200px;" class="form-control float" id="defaultFormControlInput" placeholder="Go to record" aria-describedby="defaultFormControlHelp">
<a class="goLINK" href="">Go</a>
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();
}
});
I have a textarea that triggers a function whenever the space key is pressed, that function checks if the last "bit" of text entered is an url or not and if it is it creates a preview underneath and deletes the "bit" of text from the input, that works fine, but now I want too that function to be triggered whenever the user paste something into it, the problem is that the input is linked with v-model to post.description in the data, but when #paste calls the function the data post.description is empty but when the same function is triggered by pressing the space key that data is filled...
this is the html:
<div id="post-share" class="form-group">
<textarea
id="post-description"
class="form-control"
name="post-description"
cols="40"
rows="5"
#keyup.space="checkUrl"
#paste="checkUrl"
v-model="post.description"
></textarea>
and this is the function:
checkUrl() {
if (this.post.video_link === "") {
console.log("entro 1");
let link = [];
const regex = /((?:https?:|www\.)[^\s]+)/g;
let url = this.post.description.match(regex);
console.log(this.post.description);
if (url) {
console.log("entro 2");
url.forEach((match, groupIndex) => {
link = match.split("=");
this.$set(this.post, "video_link", link[1]);
this.is_there_url = true;
this.post.description = this.post.description.replace(match, "");
});
}
}
}
so it does not meet the condition if (url) as this.post.description is empty... any hint why is only empty when trigerred by #paste and not when pressing space?
I'm not sure but maybe the #paste event is triggered before binding the value to post.description.
Try using a watcher instead
<textarea
id="post-description"
class="form-control"
name="post-description"
cols="40"
rows="5"
v-model="post.description"
></textarea>
and then in the script section add
computed:{
postDescription(){
return this.post.description
}
},
watch: {
postDescription() {
this.checkUrl()
}
}
I don't know the model you are trying to achieve but you have to add conditions on the watcher to prevent the execution of the method on every new character added to improve the performance.
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 -_-
I am working on bar-code scanners. The bar-code scanner that I am using is a plug-n-play type and scans the code automatically wherever you place the cursor. But what i want is that whether i can scan it to a specific text-box on a web page everytime my scanner reads a code
For eg, if my form looks like this
<input type="text" name="txtItem" id="txtItem" class="m-wrap w-120" tabindex="6">
<input type="text" name="itemId" id="itemId" class="m-wrap w-120" tabindex="6">
<input type="text" name="itemName" id="itemName" class="m-wrap w-120" tabindex="6">
<input type="text" name="itemQty" id="itemQty" class="m-wrap w-120" tabindex="6">
so everytime i scan a code it should always appear in the txtitem text-box no matter where my current focus is.
Can anybody guide me or help me find a solution here??
Some Barcode Scanners act just like another input device. The form cannot tell the difference between information being entered by a keyboard vs. a scanner unless you use a timer to monitor how quickly it is entered.
Some scanners "paste" the values in to the focused control - others send each individual key stroke.
The following JSFiddle is able to detect when input occurs when characters are sent individually on a single control:
http://jsfiddle.net/PhilM/Bf89R/3/
You could adapt this to make it a delegate for the whole form and remove the input from the control it was input into and put it into the correct form.
The test html for the fiddle is this:
<form>
<input id="scanInput" />
<button id="reset">Reset</button>
</form>
<br/>
<div>
<h2>Event Information</h2>
Start: <span id="startTime"></span>
<br/>First Key: <span id="firstKey"></span>
<br/>Last Ley: <span id="lastKey"></span>
<br/>End: <span id="endTime"></span>
<br/>Elapsed: <span id="totalTime"></span>
</div>
<div>
<h2>Results</h2>
<div id="resultsList"></div>
</div>
The Javascript for the sample fiddle is:
/*
This code will determine when a code has been either entered manually or
entered using a scanner.
It assumes that a code has finished being entered when one of the following
events occurs:
• The enter key (keycode 13) is input
• The input has a minumum length of text and loses focus
• Input stops after being entered very fast (assumed to be a scanner)
*/
var inputStart, inputStop, firstKey, lastKey, timing, userFinishedEntering;
var minChars = 3;
// handle a key value being entered by either keyboard or scanner
$("#scanInput").keypress(function (e) {
// restart the timer
if (timing) {
clearTimeout(timing);
}
// handle the key event
if (e.which == 13) {
// Enter key was entered
// don't submit the form
e.preventDefault();
// has the user finished entering manually?
if ($("#scanInput").val().length >= minChars){
userFinishedEntering = true; // incase the user pressed the enter key
inputComplete();
}
}
else {
// some other key value was entered
// could be the last character
inputStop = performance.now();
lastKey = e.which;
// don't assume it's finished just yet
userFinishedEntering = false;
// is this the first character?
if (!inputStart) {
firstKey = e.which;
inputStart = inputStop;
// watch for a loss of focus
$("body").on("blur", "#scanInput", inputBlur);
}
// start the timer again
timing = setTimeout(inputTimeoutHandler, 500);
}
});
// Assume that a loss of focus means the value has finished being entered
function inputBlur(){
clearTimeout(timing);
if ($("#scanInput").val().length >= minChars){
userFinishedEntering = true;
inputComplete();
}
};
// reset the page
$("#reset").click(function (e) {
e.preventDefault();
resetValues();
});
function resetValues() {
// clear the variables
inputStart = null;
inputStop = null;
firstKey = null;
lastKey = null;
// clear the results
inputComplete();
}
// Assume that it is from the scanner if it was entered really fast
function isScannerInput() {
return (((inputStop - inputStart) / $("#scanInput").val().length) < 15);
}
// Determine if the user is just typing slowly
function isUserFinishedEntering(){
return !isScannerInput() && userFinishedEntering;
}
function inputTimeoutHandler(){
// stop listening for a timer event
clearTimeout(timing);
// if the value is being entered manually and hasn't finished being entered
if (!isUserFinishedEntering() || $("#scanInput").val().length < 3) {
// keep waiting for input
return;
}
else{
reportValues();
}
}
// here we decide what to do now that we know a value has been completely entered
function inputComplete(){
// stop listening for the input to lose focus
$("body").off("blur", "#scanInput", inputBlur);
// report the results
reportValues();
}
function reportValues() {
// update the metrics
$("#startTime").text(inputStart == null ? "" : inputStart);
$("#firstKey").text(firstKey == null ? "" : firstKey);
$("#endTime").text(inputStop == null ? "" : inputStop);
$("#lastKey").text(lastKey == null ? "" : lastKey);
$("#totalTime").text(inputStart == null ? "" : (inputStop - inputStart) + " milliseconds");
if (!inputStart) {
// clear the results
$("#resultsList").html("");
$("#scanInput").focus().select();
} else {
// prepend another result item
var inputMethod = isScannerInput() ? "Scanner" : "Keyboard";
$("#resultsList").prepend("<div class='resultItem " + inputMethod + "'>" +
"<span>Value: " + $("#scanInput").val() + "<br/>" +
"<span>ms/char: " + ((inputStop - inputStart) / $("#scanInput").val().length) + "</span></br>" +
"<span>InputMethod: <strong>" + inputMethod + "</strong></span></br>" +
"</span></div></br>");
$("#scanInput").focus().select();
inputStart = null;
}
}
$("#scanInput").focus();
The code above does not support copy/paste, but in our situation this is unlikely to happen anyway.
You need to listen on "paste" event using jQuery
$("input").on("paste",function(e){
$("#txtItem").focus();
});
Here is a example:
http://jsfiddle.net/T6VdS/
I would think the scanner is just being seen as a text input device like a keyboard and outputting text. Unless there is a way to identify that text then the answer is likely to be that there isnt an easy solution.
If the code you are receiving is always in the same form and can be identified with a regular expression you might be able to move it into the correct box by somehow buffering the input (I would expect the scanned code to come in a series of keypresses that are far faster than a human would input) and running a regex over it...
Add a prefix to the text that the scanner outputs (almost all scanner will let you do this) and then when any input starts with that prefix you know its the scanner.
To catch the input with jquery you might do something like this:
//presuming the scanner acts like a keyboard
$(document).keypress(function (e) {
//do something to match the 'key presses'
//focus to the input and put the rest of the string in there
});
The best way is to put
data into scanned code. Almost all scanners support such programming. Many of them can be programmed via control barcodes, that printed in manual.
I use the Ctrl+Char for Symbol scanner,
F9 data F10 for Honeywel bluetooth scanner.
Wasp scanner does not support Ctrl+character combination. So I use
[Data] format for Wasp.
Then I catch the first symbol (say [ char) in program an position the cursor in search box. Upon receiving the last character (in my case ] char) send the contents of into search routine.