How do I get curent value of text element via jQuery - javascript

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;
}
});
});

Related

JS prevent firing focusout event if input didn't changed

I have the following input:
<input name="video" value="" type="text">
And attached js event:
input.focusout(function(){
loadThumbnail();
});
The problem is it triggers always when focus leaves field. Actually it's goods behavior, but didn't fit my needs, because if user didn't changed the field the event will be triggered and the request will be made on server.
I've tried to replace it with change event, but it doesn't triggers when user clean's field.
So what I need is event that will be triggered after user finished editing the field and detect cases when user cleans field or moves focus to/from it, but don't change anything.
Would you suggest a solution?
Try something like this to save the old value and compare it with new value:
var oldVal = ''
input.focusout(function () {
var newVal = input.val();
if (oldVal != newVal) {
oldVal = newVal;
loadThumbnail();
}
});
Try the below part. You will have to tweak this. I just wrote a raw code for U.
var temp='';
input.focusin(function(){
temp = input.val();
});
input.focusout(function(){
if temp != input.val() then
loadThumbnail();
});

getting new value of input field on keypressed

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.

Get textarea value once a key pressed

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);
});

Running check on empty input type of text

How would I run a check after a keypress function to see if an inputs value was empty so I can do another action.
For example.
$("input[name=amount]").keypress(function() {
$("table[name=apply]").show();
});
I want to hide the table if the user deletes all the keystrokes.
$("input[name=amount]").keyup(function() {
if (this.value == '') {
$("table[name=apply]").hide();
} else {
$("table[name=apply]").show();
}
});
You will probably want to use either the keyup or change event so the value of the text-box has changed before the event handler runs. The keypress event fires before the value of the input has changed, so for instance if the input is blank and a key is entered, the value in the event handler would still read as blank.
Here is a demo: http://jsfiddle.net/jasper/C5KPq/
Use the keyup() method to perform the check after the keystroke has finished:
$("input[name=amount]").keyup(function() {
if(this.value === ''){....}
});
If you bind to the keypress or keydown events, the value of the input inside your event handler will not yet have been affected by the keystroke. This is why you need to bind to keyup instead.
You can try this using keyup event instead of keypress because keypress will not give you the latest value.
$("input[name=amount]").keyup(function() {
//Here this points to the textbox element and value gives its content
if(this.value == ''){
$("table[name=apply]").show();
}
});
If you want to toggle the table the you can use this.
$("input[name=amount]").keyup(function() {
$("table[name=apply]").toggle(this.value != '');
});
toggle(showOrHide) - Display or hide the matched elements.
Demo
you can use the following
if( $(this).val() == "")
try:
if ($("input[name=amount]").val() == '') // input is empty

Can jQuery check whether input content has changed?

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.

Categories

Resources