keypress event not working with the last inserted character - javascript

I made this code:
$(".SermeCoopConvertirMayuscula").keypress(function (e) {
$(this).val($(this).val().toUpperCase());
regexp = /^[A-Z0-9 ]*$/;
return regexp.test($(this).val());
});
It is working fine. But when i type something it doesn't update my last inserted character. How can i make that the last character is added?
I need use the keypress event, i cant use the keyup event.

True, because when function is called the field is not updated with the value
The event is called in this steps
Keydown
Keypress
updateview
Keypress
updateview
keyup
So if you can change this event to keyup then you will get the latest value
Or, if you still want to use keypress event that you can do one thing you can use the following code
$(".SermeCoopConvertirMayuscula").keypress(function (eventObject) {
var val = $(this).val() + eventObject.key;
val =val.toUpperCase()
var regexp1 = /^[A-Z0-9 ]*$/;
var regexp2 = /^[A-Za-z0-9 ]$/;
if(regexp1.test(val) && regexp2.test(eventObject.key)) {
$(this).val(val);
}
return false;
});

Use keyup() instead. when keypress() is fired, the most recent character is still not registered in the input, so $(this).val() will not include it for the most recent event
$("input").keyup(function (e) {
$(this).val($(this).val().toUpperCase());
regexp = /^[A-Z0-9 ]*$/;
return regexp.test($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input/>

You could also try input which also takes care of various other input scenarios. Take a look at this for more details.
$(".SermeCoopConvertirMayuscula").on("input", function (e) {
$(this).val($(this).val().toUpperCase());
regexp = /^[A-Z0-9 ]*$/;
return regexp.test($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="SermeCoopConvertirMayuscula" />

Related

How to use onkeyup and onkeydown for an input tag?

I have an input field and i want to do some calculations depending upon keyup and keydown.
I tried using onkeyup and onkeydown functions, but when i press a key from the keyboard, it prints both "keyup" as well as "keydown" in the console. Is there any other function which differentiates keyup and keydown events seperately? My input tags are inside the html table.
This is my code
$('table input').on('keyup', function(){
console.log("keyup");
});
$('table input').on('keydown', function(){
console.log("keydown");
});
Would suggest not to mix jQuery and pure JavaScript. All you need is to add the keyup keydown instead of input:
$('table input').on('keyup keydown', function() {
var parent = $(this).closest('tr');
var value = parent.find('[name="item_value[]"]').val();
var amount = parent.find('[name="quantity[]"]').val();
var total_cost = value * amount;
parent.find('[name="total_cost[]"]').val(total_cost);
total_value = total_value + total_cost;
$('#total').val(total_value);
});
change input to keyup:
$('table input').on('keyup', function(){
var parent = $(this).closest('tr');
var value = parent.find('[name="item_value[]"]').val();
var amount = parent.find('[name="quantity[]"]').val();
var total_cost = value * amount;
parent.find('[name="total_cost[]"]').val(total_cost);
total_value = total_value + total_cost;
document.getElementById('total').value = total_value;
});
Read more about keyup
You don't need keyup and keydown, both will trigger with the same keycode.
You should use one or the other. The difference will be a delay in processing.
For instance, if you do KeyUp, depending on the length of time that the key is held down for, KeyUp will only trigger once that key is released - as opposed to KeyDown.
Referencing W3Schools, you can acheive this via:
(Where keycode = the Octal value defined in ASCII (https://www.genuinecoder.com/wp-content/uploads/2012/07/asciifull.gif)
(Also by running this example, you will notice that fast keyDowns and keyUps can cause conflicts within processing. You should use one or the other, never both.)
$("input").keyup(function(e){
alert(e.keyCode);
$("input").css("background-color", "pink");
});
$("input").keydown(function(e){
alert(e.keyCode);
$("input").css("background-color", "pink");
});

Transform String into Array and Select matching words inside the textarea

$('textarea').on('keyup', function(){
var ths = $(this);
var array = $(this).val().split(' ');
array.forEach(function(value){
if (value.match(/(threewords)/g)) {
ths.val().select(value);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>word twowords threewords</textarea>
What I want to do is to select the matching text inside the textarea if it matches the .match(/(threewords)/g) if I wrote word,
The problem is that I keep getting that .match() is null if there is no match or getting select is not a function if the match exists, But nothing is selected and the error occurs, How can I do what i'm trying to do properly?
$('textarea').on('keyup', function(){
var wordToSearch = 'threewords'
var reg = new RegExp('\\b' + wordToSearch + '\\b')
var indexStart = $(this).val().search(reg)
if(indexStart >= 0){
this.selectionStart = indexStart;
this.selectionEnd = indexStart + wordToSearch.length;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>word twowords threewords</textarea>
This code selects threewords if it is written in the textarea.
the match() function returns the matches in an array of strings, i put up an example to demonstrate it easier
try it like this:
$('button').on('click', function(){
console.log('click');
var tarea = $('textarea');
var r = tarea.val().match(/(word)/g);
console.log(r);
console.log('jobs done');
});
try it out on jsfiddle
what else you then want to do depends on what you need, if you just want to know if there is a match you can simply do so by checking if the returned array is empty or not.
in this case i use a button to trigger the check for convenience
edit: version without button jsfiddle
.select doesn't work like you are intending it to.
$("#target").select(value) is incorrect syntax. $("#target").select() is a valid syntax but it does not highlight anything it triggers the select event on an element with id 'target'.
The select event is fired when any text is selected, as in, clicked and dragged over by the mouse. It can be handled by attaching a handler to it:
Example:
$( "#target" ).select(function() {
$( "div" ).text( "Something was selected" ).show().fadeOut( 1000 );
});
ths.val().select(value); part of your code is not a function indeed. Hence the error.
ths.val().select(); on the other hand ends up triggering the select event on the matched value which doesn't serve your purpose.

Convert letter to lowercase letter automatically on keypress?

I want to convert letters automatically on keypress, tried this
$(document).on('keypress', function(e) {
$("#nick").val().toLowerCase();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id=nick value="">
But when I write Uppercase letters, it doesnt convert to lowercase. Where I did mistake ?
You aren't modifying the existing value. You need to re-assign the lowercase value:
$(document).on('keypress', function(e) {
var value = $("#nick").val().toLowerCase();
$("#nick").val(value);
});
Since the keypress event won't change the last character, I would suggest listening to the input event instead. The keyup event would work as well.
Example Here
$(document).on('input', function (e) {
e.target.value = e.target.value.toLowerCase();
});
Without jQuery:
Example Here
document.addEventListener('input', function (e) {
e.target.value = e.target.value.toLowerCase();
});
you gotta use the converted text somewhere, right? :)
$(document).on('keypress', function(e) {
$("#nick").val($("#nick").val().toLowerCase());
});
UPDATE
if you use keyup it'll work as desired: DEMO
$(document).on('keyup', function(e) {
$("#nick").val($("#nick").val().toLowerCase());
});
you can also use below approach.
$(document).on('keyup','#nick',function(e){
$(this).val(e.currentTarget.value.toLowerCase());
})
$(document).on('keyup','#nick',function(e){
$(this).val(e.currentTarget.value.toLowerCase());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="nick" value="">

Javascript - get value from textbox at every keypress

I have a textbox and I want to use the data in it every time something is entered; letter by letter.
What is happening is that when a value is entered, the Javascript is being executed before the value is actually put into the textbox, meaning that it always lags one character behind.
$(document).ready(
function() {
$('#test').keypress(
function() {
var value = document.getElementById('test').value;
alert(value);
});
})
<input id="test" type="text" />
Here's whats happening:
input alert
w ""
e "w"
a "we"
l "wea"
t "weal"
h "wealt"
Whereas I want it to happen dynamically; i.e. when I enter "w" I want the alert to contain "w" immediately after.
keypress happens before the change, yes. keyup happens after. Listen to that instead.
use keyup
$(document).ready(
function() {
$('#test').keyup(
function() {
var value = document.getElementById('test').value;
alert(value);
});
})
You should try keyup event, because keypress happens before symbol is being input in a textbox
Use keyup to read the valid after something has been entered. Here's how to do it with jQuery:
$(document).ready(function() {
$('#test').keyup(function() {
alert($(this).val());
});
});
Demo
Use the keyup event instead -:
$('#test').keyup(
function() {
var value = document.getElementById('test').value;
alert(value);
});
Use keyup instead, take a look at this:
http://jsfiddle.net/gEBc4/1/
use keyup instead
that will work
$(document).ready(
function() {
$('#test').keyup(
function() {
var value = document.getElementById('test').value;
alert(value);
});
})
Try using 'keyup' event instead of 'keypress'.
Change to:
$(document).ready(
function() {
$('#test').keyup(
function() {
var value = document.getElementById('test').value;
alert(value);
});
});
Working plunk.

jQuery bind to Paste Event, how to get the content of the paste

I have a jquery token tagit plugin and I want to bind to the paste event to add items correctly.
I'm able to bind to the paste event like so:
.bind("paste", paste_input)
...
function paste_input(e) {
console.log(e)
return false;
}
How can I obtain the actual pasted content value?
There is an onpaste event that works in modern day browsers. You can access the pasted data using the getData function on the clipboardData object.
$("#textareaid").bind("paste", function(e){
// access the clipboard using the api
var pastedData = e.originalEvent.clipboardData.getData('text');
alert(pastedData);
} );
Note that bind and unbind are deprecated as of jQuery 3. The preferred call is to on.
All modern day browsers support the Clipboard API.
See also: In Jquery How to handle paste?
How about this: http://jsfiddle.net/5bNx4/
Please use .on if you are using jq1.7 et al.
Behaviour: When you type anything or paste anything on the 1st textarea the teaxtarea below captures the cahnge.
Rest I hope it helps the cause. :)
Helpful link =>
How do you handle oncut, oncopy, and onpaste in jQuery?
Catch paste input
EDIT:
Events list within .on() should be space-separated. Refer https://api.jquery.com/on/
code
$(document).ready(function() {
var $editor = $('#editor');
var $clipboard = $('<textarea />').insertAfter($editor);
if(!document.execCommand('StyleWithCSS', false, false)) {
document.execCommand('UseCSS', false, true);
}
$editor.on('paste keydown', function() {
var $self = $(this);
setTimeout(function(){
var $content = $self.html();
$clipboard.val($content);
},100);
});
});
I recently needed to accomplish something similar to this. I used the following design to access the paste element and value. jsFiddle demo
$('body').on('paste', 'input, textarea', function (e)
{
setTimeout(function ()
{
//currentTarget added in jQuery 1.3
alert($(e.currentTarget).val());
//do stuff
},0);
});
Another approach:
That input event will catch also the paste event.
$('textarea').bind('input', function () {
setTimeout(function () {
console.log('input event handled including paste event');
}, 0);
});
On modern browsers it's easy: just use the input event along with the inputType attribute:
$(document).on('input', 'input, textarea', function(e){
if (e.originalEvent.inputType == 'insertFromPaste') {
alert($(this).val());
}
});
https://codepen.io/anon/pen/jJOWxg
$(document).ready(function() {
$("#editor").bind('paste', function (e){
$(e.target).keyup(getInput);
});
function getInput(e){
var inputText = $(e.target).html(); /*$(e.target).val();*/
alert(inputText);
$(e.target).unbind('keyup');
}
});
This work on all browser to get pasted value. And also to creating common method for all text box.
$("#textareaid").bind("paste", function(e){
var pastedData = e.target.value;
alert(pastedData);
} )
You could compare the original value of the field and the changed value of the field and deduct the difference as the pasted value. This catches the pasted text correctly even if there is existing text in the field.
http://jsfiddle.net/6b7sK/
function text_diff(first, second) {
var start = 0;
while (start < first.length && first[start] == second[start]) {
++start;
}
var end = 0;
while (first.length - end > start && first[first.length - end - 1] == second[second.length - end - 1]) {
++end;
}
end = second.length - end;
return second.substr(start, end - start);
}
$('textarea').bind('paste', function () {
var self = $(this);
var orig = self.val();
setTimeout(function () {
var pasted = text_diff(orig, $(self).val());
console.log(pasted);
});
});
It would appear as though this event has some clipboardData property attached to it (it may be nested within the originalEvent property). The clipboardData contains an array of items and each one of those items has a getAsString() function that you can call. This returns the string representation of what is in the item.
Those items also have a getAsFile() function, as well as some others which are browser specific (e.g. in webkit browsers, there is a webkitGetAsEntry() function).
For my purposes, I needed the string value of what is being pasted. So, I did something similar to this:
$(element).bind("paste", function (e) {
e.originalEvent.clipboardData.items[0].getAsString(function (pStringRepresentation) {
debugger;
// pStringRepresentation now contains the string representation of what was pasted.
// This does not include HTML or any markup. Essentially jQuery's $(element).text()
// function result.
});
});
You'll want to perform an iteration through the items, keeping a string concatenation result.
The fact that there is an array of items makes me think more work will need to be done, analyzing each item. You'll also want to do some null/value checks.
I do it like so, this would work on most browsers used by humans
$("#couponCode").bind("change keyup input paste",function () {
const value= document.getElementById("couponCode").value;
});

Categories

Resources