I'm using .blur() function to execute some code every time a text field loses focus (also when its value doesn't change).
Now I need to add some logic that must be executed only when text field value changes. Is there a way to combine .change() event with .blur()? Or, better, is there a way to know if the value in my text field is changed just using .blur()?
Not directly, but you can store the value on focus event..
something like
$('input')
.on('focus',function(){
// store the value on focus
$(this).data('originalValue', this.value);
})
.on('blur',function(){
// retrieve the original value
var original = $(this).data('originalValue');
// and compare to the current one
if (original !== this.value){
// do what you want
}
});
Of course you could just bind different handlers for each event..
$('input')
.on('change', function(){/*your change code*/})
.on('blur', function(){/*your blur code*/});
The event change is trigger every time that the field lose the focus and the content has change. I think what you need is to use change() instead of blur(). Take a look at this jsfiddle
$('#in').change(function(){
alert('change!');
});
If what you need is to execute the same code when the input loses the focus and when the value changes, you can combine both events
$('in').on('change blur', function(){
//code
});
you can use closure to store the previous value and compare them later
var createOnBlurFunc = function(){
var prevVal = '';
return function(e){
if(prevVal === $(this).val()){
//same value
} else {
prevVal = $(this).val();
// do something
}
}
};
$('input').blur(createOnBlurFunc());
I think this is a more generalized way, for those that are created on the fly:
var $bodyEl = $('body'), inputOldValue;
$bodyEl.on('focus', 'input, textarea, select', function () {
inputOldValue = $(this).val();
});
$bodyEl.on('blur', 'input, textarea, select', function () {
if (inputOldValue != $(this).val()) {
$(this).trigger('changeBlur');
}
});
input, textarea, select is faster than :input as a selector.
Related
I have an input text in jQuery I want to know if it possible to get the value of that input text(type=number and type=text) before the onchange happens and also get the value of the same input input text after the onchange happens. This is using jQuery.
What I tried:
I tried saving the value on variable then call that value inside onchange but I am getting a blank value.
The simplest way is to save the original value using data() when the element gets focus. Here is a really basic example:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/
$('input').on('focusin', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
});
$('input').on('change', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
Better to use Delegated Event Handlers
Note: it is generally more efficient to use a delegated event handler when there can be multiple matching elements. This way only a single handler is added (smaller overhead and faster initialisation) and any speed difference at event time is negligible.
Here is the same example using delegated events connected to document:
$(document).on('focusin', 'input', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
}).on('change','input', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
JsFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/65/
Delegated events work by listening for an event (focusin, change etc) on an ancestor element (document* in this case), then applying the jQuery filter (input) to only the elements in the bubble chain then applying the function to only those matching elements that caused the event.
*Note: A a general rule, use document as the default for delegated events and not body. body has a bug, to do with styling, that can cause it to not get bubbled mouse events. Also document always exists so you can attach to it outside of a DOM ready handler :)
Definitely you will need to store old value manually, depending on what moment you are interested (before focusing, from last change).
Initial value can be taken from defaultValue property:
function onChange() {
var oldValue = this.defaultValue;
var newValue = this.value;
}
Value before focusing can be taken as shown in Gone Coding's answer. But you have to keep in mind that value can be changed without focusing.
Just put the initial value into a data attribute when you create the textbox, eg
HTML
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
JQuery
$("#my-textbox").change(function () {
var oldValue = $(this).attr("data-initial-value");
var newValue = $(this).val();
});
I have found a solution that works even with "Select2" plugin:
function functionName() {
$('html').on('change', 'select.some-class', function() {
var newValue = $(this).val();
var oldValue = $(this).attr('data-val');
if ( $.isNumeric(oldValue) ) { // or another condition
// do something
}
$(this).attr('data-val', newValue);
});
$('select.some-class').trigger('change');
}
I found this question today, but I'm not sure why was this made so complicated rather than implementing it simply like:
var input = $('#target');
var inputVal = input.val();
input.on('change', function() {
console.log('Current Value: ', $(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
If you want to target multiple inputs then, use each function:
$('input').each(function() {
var inputVal = $(this).val();
$(this).on('change', function() {
console.log('Current Value: ',$(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
my solution is here
function getVal() {
var $numInput = $('input');
var $inputArr = [];
for(let i=0; i < $numInput.length ; i++ )
$inputArr[$numInput[i].name] = $numInput[i].value;
return $inputArr;
}
var $inNum = getVal();
$('input').on('change', function() {
// inNum is last Val
$inNum = getVal();
// in here we update value of input
let $val = this.value;
});
The upvoted solution works for some situations but is not the ideal solution. The solution Bhojendra Rauniyar provided will only work in certain scenarios. The var inputVal will always remain the same, so changing the input multiple times would break the function.
The function may also break when using focus, because of the ▲▼ (up/down) spinner on html number input. That is why J.T. Taylor has the best solution. By adding a data attribute you can avoid these problems:
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
If you only need a current value and above options don't work, you can use it this way.
$('#input').on('change', () => {
const current = document.getElementById('input').value;
}
My business aim was removing classes form previous input and add it to a new one.
In this case there was simple solution: remove classes from all inputs before add
<div>
<input type="radio" checked><b class="darkred">Value1</b>
<input type="radio"><b>Value2</b>
<input type="radio"><b>Value3</b>
</div>
and
$('input[type="radio"]').on('change', function () {
var current = $(this);
current.closest('div').find('input').each(function () {
(this).next().removeClass('darkred')
});
current.next().addClass('darkred');
});
JsFiddle: http://jsfiddle.net/gkislin13/tybp8skL
if you are looking for select droplist, and jquery code would like this:
var preValue ="";
//get value when click select list
$("#selectList").click(
function(){
preValue =$("#selectList").val();
}
);
$("#selectList").change(
function(){
var curentValue = $("#selectList").val();
var preValue = preValue;
console.log("current:"+curentValue );
console.log("old:"+preValue );
}
);
I'm using a JavaScript library that occasionally changes the value of an input field. I want to detect when that happens.
Apparently, the change and input events are not triggered when the value of an input field is changed (at least not on Chrome).
To verify that, I have tried this (using jQuery):
<script>
$(function() {
$('#inp').on('change',function() { console.log('change event'); });
$('#inp').on('input',function() { console.log('input event'); });
$('#inp').val('hello');
});
</script>
<input type="text" id="inp">
Neither the change event nor the input event is triggered when I call .val('hello').
How can I detect the change? (Please remember that the code that changes the value is outside my control, so I cannot add a call to trigger() there.)
There is a work around, you can pool the value of textbox after regular intervals and trigger the event when it is changed.
Live Demo
$('#elementId').change(function(){
alert("changed");
});
var previousVal = "";
function InputChangeListener()
{
if($('#elementId').val() != previousVal)
{
previousVal = $('#elementId').val();
$('#elementId').change();
}
}
setInterval(InputChangeListener, 500);
$('#elementId').val(3);
Edit based on comments for many elements.
You can use array and monitor, 30 element wont be a performance concern
Live Demo
$('.someclass').change(function(){
alert("changed, id >> " + this.id);
});
var hashTablePrevElem=[];
$('.someclass').each(function(){
hashTablePrevElem[this.id] = this.value;
});
function InputChangeListener()
{
$('.someclass').each(function(){
if(hashTablePrevElem[this.id] != this.value)
{
hashTablePrevElem[this.id] = this.value;
$(this).change();
}
});
}
I want to trigger an event handler once per each actual change in an input field. For example, to validate (per keypress) entry of a credit card number (the change must be on each change so debouncing/throttling is not the answer).
I cannot use input alone as IE9 will not trigger this event from backspaces or cut/delete.
I cannot use keyup alone as this does not handle changes from a mouse (eg. pasting).
I cannot use change because this only fires on blur.
I can do $('input').bind('input keyup', handler) but this will fire two separate events most of the time. Assume that the handler is expensive and running it twice is unacceptable.
I can wrap the handler so that it only runs if the current value is different to the last checked but is there a better way?
What you are doing with checking the last input is what you need to do.
This is one way you can do it to store the last value.
function handler(){
var tb = jQuery(this);
var currentValue = tb.val();
if (tb.data("lastInput") !== currentValue) {
tb.data("lastInput", currentValue);
console.log("The current value is " + currentValue);
}
}
$('input').bind('input keyup', handler);
jsFiddle
You could always extend jQuery if you really do not want that logic in your function. It is a bunch more code, but one method.
(function(){
$.fn.oneinput = function(callback) {
function testInput(){
var tb = jQuery(this);
var currentValue = tb.val();
if (tb.data("lastInput") !== currentValue ) {
tb.data("lastInput",currentValue );
if(callback) {
callback.call(this)
};
}
return this;
}
jQuery(this).bind("keyup input", testInput);
};
}(jQuery));
$('input').oneinput( function(){ console.log(this.value); });
jsfiddle
I think the you have to use setInterval to moniter the change in the text box
try this demo
objTextBox = document.getElementById("trackChange");
oldValue = objTextBox.value;
console.log(oldValue);
function track_change()
{
if(objTextBox.value != oldValue)
{
oldValue = objTextBox.value;
console.log("changed")
}
}
setInterval(function() { track_change()}, 100);
Note: I don't personally think that this is the best solution.But I cant find a better and at leat it will work for sure in every case keyboard or mouse change ;)
Try this
$('input').bind('keyup cut paste', function (event) {
console.log('value changed');
});
Fiddle http://jsfiddle.net/sXvK2/1/
If you don't need the handler to return a value, you can make it return false so that it doesn't fire up a second time.
What about
$el.bind('input', handler);
$el.bind('keyup', handler);
...
I have this function:
$("#border-radius").click(function(){
var value = $("#border-radius").attr("value");
$("div.editable").click(function (e) {
e.stopPropagation();
showUser(value, '2', this.id)
$(this).css({
"-webkit-border-radius": value
});
});
});
It reads the value of a textbox,
input type="text" id="border-radius" value="20px"
...and does a few things with it that are not relevant to my problem.
The textbox has the id="border-radius", and when it is clicked (and has a value) the function executes, as shown: $("#border-radius").click(function(){ ...do some stuff...
Basically, I want to be able to type a value into the textbox, and then click an object (submit button or div, preferably a div) and have it execute the function after: $("#border-radius").click(function(){ ...do some stuff... Instead of having to click the textbox itself
What can I add/change to enable this?
I think you need to identify the event target.
that you can do it by
event target property
example
$(document).ready(function() {
$("#border-radius").click(function(event) {
alert(event.target.id);
//match target id and than proceed futher
});
});
Put the click handler on #my-button or whatever your button is.
$("#my-button").click(function(){
var value = ... /* your original code */
});
It will still work because you are getting the value like $("#border-radius").attr("value"); and not $(this).attr("value");. So you all you need to change is which element you attach the click function to.
Alternatively, if you want to keep both handlers, you can just use it for both elements like this:
var commonHandler = function(){
var value = ... /* your original code */
};
$("#border-radius").click(commonHandler);
$("#my-button").click(commonHandler);
You can also trigger the click event of #border-radius, but this will execute all the event handlers attached on it:
$("#my-button").click(function () {
$("#border-radius").click();
// or $("#border-radius").trigger('click');
});
I would like a span to update when a value is entered into a text field using jquery.
My form field has a text box with the name "userinput" and i have a span with the id "inputval".
Any help would be greatly appreciated.
UPDATE:
although you marked this as the correct answer, note that you should use the keyup event rather than the change event or the keydown
$(document).ready(function() {
$('input[name=userinput]').keyup(function() {
$('#inputval').text($(this).val());
});
});
Try the following, you have to call again keyup() to trigger for the last char:
$(".editable_input").keyup(function() {
var value = $(this).val();
var test = $(this).parent().find(".editable_label");
test.text(value);
}).keyup();
Try this. Be sure that you understand what is going on here.
// when the DOM is loaded:
$(document).ready(function() {
// find the input element with name == 'userinput'
// register an 'keydown' event handler
$("input[name='userinput']").keydown(function() {
// find the element with id == 'inputval'
// fill it with text that matches the input elements value
$('#inputval').text(this.value);
}
}
$(function() {
$("input[name=userinput]").keydown(
function() {
$('#inputval').text(this.value);
}
)
})