jQuery Change event on an input element - any way to retain previous value?
A better approach is to store the old value using .data. This spares the creation of a global var which you should stay away from and keeps the information encapsulated within the element. A real world example as to why Global Vars are bad is documented here
e.g
<script>
//look no global needed:)
$(document).ready(function(){
// Get the initial value
var $el = $('#myInputElement');
$el.data('oldVal', $el.val() );
$el.change(function(){
//store new value
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
})
.focus(function(){
// Get the value when input gains focus
var oldValue = $(this).data('oldVal');
});
});
</script>
<input id="myInputElement" type="text">
Input jQuery get old value before onchange and get value after on change
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 :)
JQuery onChange get previous value
I'm thinking... Array in an object!
You could have an array defined in a javascript object
var inputObj =
{
var index : -1; //When the input has nothing so far
var values : [];
};
And then everytime the input changes
$('#p1').on('change', function() {
var cost = $('#p1_price').text();
var quantity = $('#p1').val();
var total = cost * quantity;
total = parseFloat(total).toFixed(2)
$('#p1_total').text(total);
$('#total_price').text(+$('#total_price').html() + +cost);
//Add a new value to the array and refresh the index of the current value
inputObj.values.add(total);
inputObj.index = inputObj.values.length + 1;
});
And everytime you press the down button:
function pressDown()
{
inputObj.index = inputObj.index - 1;
$('#p1_total').text(inputObj.values[inputObj.index]);
}
how to get previous value of textbox in jquery on change event
You almost got this right, but you forgot to update the data-old
in your code, below is an example and jsbin
$(".whitebox").on('change', function (event) {
// on first change will be empty string
// as no previous value was set
var oldValue = event.target.dataset.old;
console.log('old value', oldValue);
// your code here
// at the end assign new value to data-old attribute
$(this).data('old', event.target.value);
console.log(event.target.value);
});
http://jsbin.com/jasaqiwuwo/
jQuery: how to get new value, but not old value at on('save') event?
A div will never trigger a change
event, as that's reserved for inputs the user can manipulate.
If you still want to listen to changes made to the inner HTML of a div, you can try the following, while that may not work in Internet Explorer or older browsers at all:
$(function() {
$('div.editable').on('DOMSubtreeModified'), function(e) {
console.log(e.target.getAttribute('data-pk')+' '+e.target.text+' '+e.target.getAttribute('name'));});
}
}
Be careful not to overwrite the div's content inside the event handler, or you will cause an infinite loop. I suggest expanding your knowledge on the DOMSubtreeModified
event by reading, for example, the MDN article: link
How to get old Value with onchange() event in text box
element.defaultValue
will give you the original value.
Please note that this only works on the initial value.
If you are needing this to persist the "old" value every time it changes, an expando property or similar method will meet your needs
jQuery change event logic on getting previous value?
Perhaps if you
- use prop
- do NOT remove the prop
- simplify your logic
- use a more recent version of jQuery
$(window).load(function() { var $indicator = $("#indicator"); // if you have colons, use #mypage\\:indicator var $reason = $("#reason");
// set the pre data, usually needed after you initialize the select element $indicator.data("prev", $indicator.val());
// Handle initial status of indicator, when page load, if it is 'N' disable // reason field, if it is 'Y' open reason field $reason.prop('disabled', $indicator.data("prev") == 'N');
// Handle change status of indicator, $indicator.on("change", function(data) { var jqThis = $(this);
// get changed data var after_change = jqThis.val();
// get the pre data (Question : I expect the pre data should be original page load value, but // seems it always the latest one before current value ?) // e.g when page load, indicator is 'N', user first change it to 'Y', then change back to 'N', but // the pre data value will be 'Y', not what I expect as original page load initial value 'N' // I use a pop up dialog to observe this issue.
var before_change = jqThis.data("prev");
// Debug console.log("before:", before_change);
// do your work here /* var dis = (before_change == 'N' && after_change == 'Y') || (before_change == 'Y' && after_change == 'N') || (before_change == 'Y' && after_change == 'Y') */ var dis = !(before_change == 'N' && after_change == 'N'); $reason.prop('disabled', dis);
// update the pre data jqThis.data("prev", after_change); });});
.htmlClass { padding: 8px; border: 1px solid blue; margin-bottom: 8px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><form name="myform"> <div align="center"> <select id="indicator"> <option value="Y">Yes</option> <option value="N">No</option> </select> <textarea id="reason"> </textarea></form>
Get previous value of dropdown after onchange event jQuery
Best way to do it by jquery :
$(document).ready(function(){
var previous;
$("#Diabetes_UK_3147").on("focus click",function () {
previous = this.value; // Old vaue
}).change(function() {
var value = this.value; // New Value
$('span').text('Old Value : '+previous+' New Value : '+value)
});
})
here the fiddle http://jsfiddle.net/Laa2hL3b/
Edited : in auto-Generated dropdown you can add a custom class for example "myselectbox"
<select class="form-control myselectbox"
and make change here
$(".myselectbox").on(/* other code remain same */
Get the old value of a widget from onChange event?
What you need is watch(), it will give you both newValue and oldValue.
<script type="dojo/watch" data-dojo-prop="value" data-dojo-args="prop,oldValue,newValue">
document.getElementById("statusContainer").innerHTML = "Old Value: " + oldValue + ", New Value: " + newValue;
</script>
I have updated your fiddle here. Hope it helps.
FYI, your other solution won't work if I am using only keyboard (tabs to gain focus) and change the value.
Related Topics
Check If Url Scheme Is Supported in JavaScript
React Hooks - Right Way to Clear Timeouts and Intervals
JavaScript Regex Hangs (Using V8)
Settimeout Ignores Timeout? (Fires Immediately)
Limited Parallelism with Async/Await in Typescript/Es7
How to Insert a Character After Every N Characters in JavaScript
Date VS New Date in JavaScript
Check If Event Is Triggered by a Human
Track Event in Google Analytics Upon Clicking Form Submit
What's the Fastest Way to Convert String to Number in JavaScript
How to Programmatically Force an Onchange Event on an Input
How to Check If the Array of Objects Have Duplicate Property Values
Overriding a JavaScript Function While Referencing the Original
Difference Between Window.Location.Href=Window.Location.Href and Window.Location.Reload()
How to Detect If a Variable Is an Array
Why Is My Onclick Being Called on Render? - React.Js