One-( keypress-)event-delay between javascript input and output - javascript

The following snippet reproduces the input text in the webpage using simple javaScript and jQuery.
I am wondering, though, how come there is a one character (or more precisely : one keystroke) latency between the input and the output
eg :
I type 'abcde'
the output is 'abcd'
however if I press the Insert key, the ultimate 'e' prints.
My code :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<input type="text" name="enteredText" id="myTextInput" />
<p id="myTextOutput">
blabla
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("#myTextInput").keypress(function( ){
var theText = $("#myTextInput").val();
$("#myTextOutput").html(theText);
});
$( "html" ).click(function( event ) {
var value = $("#myTextInput").val();
$("#myTextOutput").html(value);
});
</script>
</body>
</html>
Any idea ? Thanks

If you want to get rid of tat latency. use keyup or keydown instead of keypress:
$("#myTextInput").keyup(function( ){
var value = $("#myTextInput").val();
$("#myTextOutput").html(value);
});
Here is the DEMO

The most likely reason is that the keypress event handler is executed before the content of the input field is updated. When you read the content, you still read the old content, not the updated one.
From jQuery's keypress docs:
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
Using keyup instead fixes the issue:
$("#myTextInput").keyup(function() {
var theText = $("#myTextInput").val();
$("#myTextOutput").html(theText);
});
$("html").click(function(event) {
var value = $("#myTextInput").val();
$("#myTextOutput").html(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="enteredText" id="myTextInput" />
<p id="myTextOutput">
blabla
</p>

You're grabbing the value before you've allowed the event to propagate up to where the text field has been updated. You can add an infinitesimal delay to get the full value:
$("#myTextInput").keypress(function( ){
setTimeout(function() {
var value = $("#myTextInput").val();
$("#myTextOutput").html(value);
}, 0);
});

Related

Trigger onKeyUp from script after input value is changed

I have a few input fields that use onKeyUp="script" to return data the moment something is entered.
As a shortcut, I would like to be able to add a value to one of the fields when data is entered from another location AND trigger the script.
I can use document.getElementById("myID").value = MyValue; to add a specific value to the input box, or .addEventListener(); to watch another input field.
This part works well.
However, I have not been able to trigger anything equivalent to onKeyUp, which will happen either when:
1. You press/release a key while the input field is in focus.
2. You focus the input and release a key AFTER the script has added a value.
3. You enter the input field via [TAB] AFTER the script has added a value.
Adding .keyup(); or .keypress(); have had no effect.
I've been able to use .focus(); to focus and then change the input, but this does not have the same effect as pressing [TAB]
What can I do to trigger the onKeyUp for this field, even if the data was not manually typed?
ADDITIONAL INFO
This part works...
<input type="text" id="box1" onKeyUp="script1();">
<div id="result1" "> (script places result here) </div>
Add value from another location - Option 1
<input type="text" id="Test1">
<button type="button" onclick="TestScript()"> TEST</button>
<script type='text/javascript'>
function TestScript() {
var test1=document.getElementById("Test1").value;
document.getElementById("box1").value = test1;
document.getElementById("box1").keyup();
return false;
}
</script>
Add value from another location - Option 2
<script type='text/javascript'>
window.onload = function () {
document.getElementsByName("box2")[0].addEventListener('change', TestScript2);
function TestScript2(){
var test2=document.getElementById("box2").value;
document.getElementById("box1").value = test2;
}}
</script>
Both of these options will copy the value to the correct location, but I have not been able to get either to trigger the onKeyUp so that the original script realizes something has changed.
Non working Fiddle example: https://jsfiddle.net/mj8g4xa2/4/
Trigger keyup programatically in;
JAVASCRIPT:
Call onkeyup() on the element.
Create a new keyup event and dispatch it using the element. Note: The source here doesn't support IE. Refer this answer for cross-browser support. Also createEvent is deprecated (MDN Docs for reference).
JQUERY:
$("#elem").keyup();
$("#elem").trigger('keyup');
Change events fire only when the input blurs, according to the MDN Docs.
Also, you should have got Uncaught TypeError: element.keyup is not a function error in your console.
var elem = document.getElementById("data");
function triggerKeyUpEvent()
{
var e = document.createEvent('HTMLEvents');
e.initEvent("keyup",false,true);
elem.dispatchEvent(e);
}
function perform()
{
console.log("KeyUp");
}
function add()
{
elem.value = String.fromCharCode(Math.random().toFixed(2)*100).repeat(5);
elem.onkeyup();
triggerKeyUpEvent();
}
<input id="data" onkeyup="perform()">
<button id="add" onclick="add()">Add Random Data</button>
To fix your JSFiddle update the following code:
var elem = document.getElementById("sim1");
function triggerKeyUpEvent() {
var e = document.createEvent('HTMLEvents');
e.initEvent("keyup",false,true);
elem.dispatchEvent(e);
}
function add() {
var sim1=document.getElementById("sim1").value;
document.getElementById("box1").value = sim1;
elem.onkeyup();
triggerKeyUpEvent()
}
by replacing the line elem.dispatchEvent(e) with box1.dispatchEvent(e)
And the line elem.onkeyup() with box1.onkeyup()
Lastly, it would seem that you don't need to call triggerKeyUpEvent as when I removed it, it still works.
Here's the udpated JSFiddle

General script: selecting the input element for which keypress event is fired, without actually passing the ID etc

I am writing a general Jquery script for validation and I am stack at selecting the element for which the keypress event is fired, without actually passing the ID element #elementid specified in the below code.-->var element = **pick the object**// $('input[type=number][validate=something]');.
Note that the below code pickup all the input field of number type and attribute value of validation assomething.
get the value of maxlength of the field for which keypress event has occured.
avoid java script function call inside input.
write a general script that could be applicable for all page and not pick element by id attribute.
Sample JS below
<!DOCTYPE html>
<html>
<head>
<title>Validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<input validate="something" type="number" maxlength="9" />
<input validate="something" type="number" maxlength="9" />
<script>
$('input[type=number][validate=something]').on('keypress', function(evt,obj) {
var element =**pick the object**// $('input[type=number][validate=SSN]');
var len = element.val().length + 1;
var max = element.attr("maxlength");
if (!(len <= max)) {
// some code
}
});
</script>
</body>
</html>
The element you've hooked the event on is available within the handler as this; to wrap it in an jQuery object, use $():
var element = $(this);

How to get a substring from the text of an input field and display it to another html element

var str1=$("#account-number").val().substring(0,4);
$("#first-four").html(str1);
I have tried multiple variations and attempts its been a few hours... so I thought I should ask for help...
I want to be able to take the first four characters of an input field with id "account-number" and send it to a div with id "first-four"
On thing to watch out for is change vs input. The first only fires when the input looses focus.
$("#account-number").on("input", function(){
$("#first-four").text(this.value.substring(0,4));
});
<input id="account-number" type="text" />
<div id="first-four"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).ready(function(){
$("#account-number").blur(function(){
var accountNmbr = $("#account-number").val().substring(0,4);
$("#first-four").html(accountNmbr);
});
});
JSFiddle: https://jsfiddle.net/Lw4kr4Lq/
$( document ).ready(function() {
$( "#account-number" ).on("input", function() {
var str1 = $("#account-number").val().substring(0,4);
$("#first-four").html(str1);
});
})

Adding and removing a tag on function call

I need to change the color of a specific word inside a text of an element. I tried adding and removing span tags to change the style of the word, but I can't remove it after. Here's the code I tried
function changeColor(unit){
document.getElementsByClassName("label")[0].innerHTML=document.getElementsByClassName("label")[0].innerHTML.replace('/<span id="highlighted">(.*)<\/span>/g','$1');
document.getElementsByClassName("label")[0].innerHTML=document.getElementsByClassName("label")[0].innerHTML.replace(unit,'<span id="highlighted">' + unit + '</span>');
}
The text looks like this "°C,kW/h,cm".
What is happening right now is everytime the function is called, span tags are added but never removed. How can I achieve this with Javascript/JQuery?
Desired behavior :
When the function is called with say "cm" as parameter. I want the string to become "°C,kW/h,<span id=highlighted>cm</span>". Now if the function is called again with "kW/h", I want the string to become "°C,<span id=highlighted>kW/h</span>,cm"
With jQuery you can use .unwrap():
Try:
$(document).ready(function(){
$("label span").contents().unwrap()
});
label {color:green}
#highlighted{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<label>°C,<span id=highlighted>kW/h</span>,cm</label>
Change
.replace('/<span id="highlighted">(.*)<\/span>/g','$1')
to
.replace(/<span id="highlighted">(.*)<\/span>/g,'$1')
The first one is a string, the second one a RegEx and you need the latter.
See how replace works. The first argument is either a string or a RegEx.
Adding my no-jQuery solution:
Make 3 spans (s1, s2, s3)
Change the color style depending on the unit input
And so:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
function changeColor(unit) {
var allUnits = [ '°C', 'kW/h', 'cm' ];
for (var i = 0; i < allUnits.length; i++) {
if (unit == allUnits[i])
document.getElementById('s'+(i+1)).style = 'color:#00FFFF';
else
document.getElementById('s'+(i+1)).style = 'color:#000000';
}
}
document.addEventListener("DOMContentLoaded", function(event) {
changeColor('kW/h');
});
</script>
</head>
<body>
<span id="s1">°C</span>,<span id="s2">kW/h</span>,<span id="s3">cm</span>
</body>
</html>

Get a variable immediately after typing

I have this code
<span></span>
and this
<div> variable like a number </div>
and
<script>
$(document).ready(function(){
var x = $('div').html();
$('span').html(x)
});
</script>
I need that every time I change the div value, the span reflects the changes of the div
For example.
If I type 1 in the div, the span should immediately show me number 1
If I type 3283 in the div, the span should immediately show me number 3283
but with this code - I need to create
$("div").click(function(){
var x = $('div').html();
$('span').html(x)
});
I do not want to use .click(function) . in need this function run Automatically
after your answer
I use this code
http://jsfiddle.net/Danin_Na/uuo8yht1/3/
but doesn't work . whats the problem ?
This is very simple. If you add the contenteditable attribute to the div, you can use the keyup event:
var div = $('div'),
span = $('span');
span.html(div.html());
div.on('keyup', function() {
span.html(div.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span></span>
<div contenteditable="true"> variable like a number </div>
here is a demo with input:
html:
<span></span>
<input type="text" id="input01">
js:
$(document).ready(function(){
$( "#input01" ).on('keyup',function() {
var x = parseFloat($('#input01').val());
$('span').html(x)
});
});
How can you edit in div element on browser?
It have to be any input type then only you can edit or change value.
So for that on click of that div you have to show some input/textarea at that place and on change event of that input you can update the value of input in span.
<div id="main-div">
<input type="text" id="input-box" />
</div>
<script>
$(document).ready(function(){
$('#input-box').change(function(){
$('span').html($(this).text)
});
});
</script>
$("input[type=text]").change(function(){
var x = $('div').html();
$('span').text(x)
});
This can be use with textbox or textarea, For div user cannot enter text.
http://jsfiddle.net/uuo8yht1/
.change() will not work with a DIV-element. Since you did not specify how the DIV is updated I would recommend either setting a timer or using .keypress()
Example with timer:
$(function(){
var oldVal = "";
var divEl = $("div");
setInterval(function(){
var elTxt = divEl.text();
if (elTxt != oldVal) {
oldVal = elTxt;
$("span").text(elTxt);
}
}, 50);
});
You need a key listener, jquery provides a .keypress(), Examples are provided on keypress documentation.
I recommend to lookup the combination of .on() and .keyup() with some delay or throttle/debounce either via jquery or underscore.js library.
One of the reason or need for delay is to prevent too many event calls which will affect performance.
Here is an example of code in another question regarding throttle and keyup
Hope this helps.

Categories

Resources