I have an function executed after a keypress event :
$("#txtarea").keypress(function(){
alert(document.getElementById("txtarea").value);
});
I want to return the new text of the textarea after every keypress, so that it can be used simultanuously in other javascript functions.
The problem with this script is that once a key is pressed, the function displays "" empty string.
Thank you in advance.
Try to use keyup instead of keypress
The keypress just get fired before the value assigned.
Like every other event(click, submit etc'...) so you can cancel the default behavior and "stuff"
$('#txtarea').keypress(function(event) {
return false; // this will disable the new value assignment
});
You can find out what button was clicked with event.which and work with it.
Example:
<input id="txtarea" />
$('#txtarea').keypress(function(e){
var value = this.value;
alert(value);
alert(value + String.fromCharCode(e.which))
});
JSFiddle DEMO
You can also use the keyup event, but it has other meaning and usage than keypress.
Be aware!
You can use this code, note keyup rather than keypress as this means the key has been added to the textarea:
$('#txtarea').keyup(function() {
alert(this.value);
});
Also, no need to do the document.getElementById, just use this.value
http://jsfiddle.net/A8XxK/1
Perform the behaviour after a zero-length timeout.
$("#txtarea").keypress(function(){
setTimeout(function () {
alert(document.getElementById("txtarea").value);
}, 0);
});
Related
I want to perform toUpperCase() each time the content of an input field is changed. I mean not when the field lost focus, but each time a character is typed.
I try this which doesn't work (I'm fairly new to JQ)!
$(".myClass").change(function () {
$(this).val().toUpperCase();
});
Besides the function is launched only on blur.
What's wrong?
$('.myClass').on('input', function() {
$(this).val($(this).val().toUpperCase());
});
Function will fire change event but You need to reset that value using .val() as just setting the text to toUpperCase() isn't enough.
$(".myClass").change(function () {
$(this).val($(this).val().toUpperCase());
});
Fiddle Demo
To limit the characters in the browser input to upper case, use css-
someinput{text-transform:uppercase}
Then use any change event or a validation before submitting to change the value you are sending to the server.
You should use another keyboard event:
https://api.jquery.com/keypress/
$( "#test" ).keypress(function(e) {
$(this).val($(this).val().toUpperCase());
});
i have an input field where i allow users to insert an integer.
Now when ever they insert a value into the input field i check with ajax if it is higher than a specefic amount for this purpose i need to get the "new" value of the input field
i have tried the following:
$('.wanted_amount').keydown(function () {
var value = $(this).val();
}
however this returns ""
Meaning that it doesnt register the value untill after keydown
So how i can i get the new value of the input field with javascript?
can you please try this,
$(function(){
$('.wanted_amount').keyup(function () {
var value = $(this).val(); // alert(value);
});
});
keydown is event, which helps to trigger event when detects a finger on a key
keyup is event, which helps to trigger event when the key is released
You have not closed function properly.
keydown() will be triggered when key is pressed and keyup() will be triggered after pressing the key. In your case, keyup() is more suitable.
Try this:
$('.wanted_amount').keyup(function () {
var value = $(this).val();
console.log(value);
});
Fiddle here.
I have text input element and an event is fired on blur event and when user presses enter.
My problem is that if user inputs "foo" and presses enter val() function nevertheless returns null, after the blur event val() returns foo. As far as I understand it is due to the fact that value property of HTML input element is updated only when it looses focus. Could you please give me a work around.
Here is the exact code I use:
var meetmove_address_field_listener = function(e){
var type = $(this).attr('data-marker-type');;
var value = $(this).val();
meetmove_map.geocodeAddress(type, value);
};
$(document).ready(function(){
$('input[data-type="name"]').blur(meetmove_address_field_listener);
$('input[data-type="name"]').keypress(function(event){
if (event.which == 13){
event.preventDefault();
meetmove_address_field_listener(event);
return false;
}
});
});
The value can be accessed straight away, you just need to use the correct handler. .keypress() will fire before the character is displayed in the input. Try .keyup() instead of .keypress() and it should work.
Well really Sudahir answer solved my issue --- i was misusing $(this) reference that changes meaning depending on context. Bu he deleted his answer so here is the working code:
$(document).ready(function(){
$('input[data-type="name"]').blur(meetmove_address_field_listener);
$('input[data-type="name"]').keyup(function(event){
if (event.which == 13){
event.preventDefault();
var type = $(this).attr('data-marker-type');
var value = $(this).val();
meetmove_map.geocodeAddress(type, value);
return false;
}
});
});
Is it possible to bind javascript (jQuery is best) event to "change" form input value somehow?
I know about .change() method, but it does not trigger until you (the cursor) leave(s) the input field. I have also considered using .keyup() method but it reacts also on arrow keys and so on.
I need just trigger an action every time the text in the input changes, even if it's only one letter change.
There is a simple solution, which is the HTML5 input event. It's supported in current versions of all major browsers for <input type="text"> elements and there's a simple workaround for IE < 9. See the following answers for more details:
jQuery keyboard events
Catch only keypresses that change input?
Example (except IE < 9: see links above for workaround):
$("#your_id").on("input", function() {
alert("Change to " + this.value);
});
Yes, compare it to the value it was before it changed.
var previousValue = $("#elm").val();
$("#elm").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
alert("Value changed!");
}
});
Another option is to only trigger your changed function on certain keys. Use e.KeyCode to figure out what key was pressed.
You can also store the initial value in a data attribute and check it against the current value.
<input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" />
$("#id_someid").keyup(function() {
return $(this).val() == $(this).data().initial;
});
Would return true if the initial value has not changed.
function checkChange($this){
var value = $this.val();
var sv=$this.data("stored");
if(value!=sv)
$this.trigger("simpleChange");
}
$(document).ready(function(){
$(this).data("stored",$(this).val());
$("input").bind("keyup",function(e){
checkChange($(this));
});
$("input").bind("simpleChange",function(e){
alert("the value is chaneged");
});
});
here is the fiddle http://jsfiddle.net/Q9PqT/1/
You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):
$(document).ready(function() {
$("#fieldId").bind("keyup keydown keypress change blur", function() {
if ($(this).val() != jQuery.data(this, "lastvalue") {
alert("changed");
}
jQuery.data(this, "lastvalue", $(this).val());
});
});
This would work pretty good against a long list of items too. Using jQuery.data means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc") to track many fields.
UPDATE: Added blur to the bind list.
I had to use this kind of code for a scanner that pasted stuff into the field
$(document).ready(function() {
var tId,oldVal;
$("#fieldId").focus(function() {
oldVal = $("#fieldId").val();
tId=setInterval(function() {
var newVal = $("#fieldId").val();
if (oldVal!=newVal) oldVal=newVal;
someaction() },100);
});
$("#fieldId").blur(function(){ clearInterval(tId)});
});
Not tested...
I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier.
You can set events on a combination of key and mouse events, and onblur as well, to be sure. In that event, store the value of the input. In the next call, compare the current value with the lastly stored value. Only do your magic if it has actually changed.
To do this in a more or less clean way:
You can associate data with a DOM element (lookup api.jquery.com/jQuery.data ) So you can write a generic set of event handlers that are assigned to all elements in the form. Each event can pass the element it was triggered by to one generic function. That one function can add the old value to the data of the element. That way, you should be able to implement this as a generic piece of code that works on your whole form and every form you'll write from now on. :) And it will probably take no more than about 20 lines of code, I guess.
An example is in this fiddle: http://jsfiddle.net/zeEwX/
Since the user can go into the OS menu and select paste using their mouse, there is no safe event that will trigger this for you. The only way I found that always works is to have a setInterval that checks if the input value has changed:
var inp = $('#input'),
val = saved = inp.val(),
tid = setInterval(function() {
val = inp.val();
if ( saved != val ) {
console.log('#input has changed');
saved = val;
},50);
You can also set this up using a jQuery special event.
I have an <input type="text">, and I need to call a function after the text in the text box was changed (inluding actions performed during jQuery's keydown and keypress handlers).
If I call my function from the jQuery handler, I see the value (e.target.value) as it was before the input was added. As I don't want to manually add the input onto the value every time, how I can call my function and have it use the updated value?
If I understand you right then something like this is the way u can do it
$('input').bind('change keydown keyup',function (){
/// do your thing here.
// use $(this).val() instead e.target.value
});
Updated: 03/05/13
Please note: that you are better off to use .on() as oppose to .bind()
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
For more information jQuery Bind
You can use keyup - so you are only calling it once the key has been released:
$("#idofinputfield").keyup(function() {
youFunction($(this).val());
});
You can generate the future value by taking the position where the new character will be inserted:
$('input').bind('keypress',function (){
var value = e.target.value,
idx = e.target.selectionStart,
key = e.key;
value = value.slice(0, idx) + key + value.slice(idx + Math.abs(0));
return yourfunction(value);
});
Have u tried out
$('#target').keyup(function(){
alert($(this).val());
});
if you need to bind to an element up in the hierarchy, you can subscribe to the keyUp event in the keyDown handler.
$("#container").keydown(function (e) {
//here you decide whether to handle the key event, and grab the control that sent the event
var myInput = e.target;
$("#container").one('keyup', function() {
console.log(myInput.val());
// do smth here
});
});
You should use event.key to get the current input value before it is displayed in textbox.
Here is the code.
function validate()
{
document.getElementById("divOutput").innerHTML = event.key;
//I am here returning false so that you can see that this value is being entered before the text is input. This is very useful for number validation purposes.
return false;
}
Enter Number: <input type="text" id="txtInput" onkeydown="return validate()" /><br />
You Entered <div id="divOutput"></div>