Reputation: 1364
I need your help,
I am new to jQuery and I am not sure as to how I would go about getting the previous text that was entered in either 3 of the text boxes.
Here is the javascript along with the HTML coding:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function() {
$('#one, #two, #three').change(function(e) {
alert(e.target.value)
});
}
</script>
</head>
<body>
<input type="text" id="one">
<input type="text" id="two">
<input type="text" id="three">
</body>
</html>
Upvotes: 1
Views: 196
Reputation: 395
You could store the old value in a data-attribute on the element
$('#one, #two, #three').change(function(e) {
alert($(e.target).data('oldVal'))
$(e.target).data('oldVal', e.target.value)
})
Though the initial value will be undefined, so you could either accept that or have some init code to set it to "" for the elements depending on your requirements
Also just an FYI because you said you're new to jQuery
$('.preserves-old-value').change(function(e) {
alert($(e.target).data('oldVal'))
$(e.target).data('oldVal', e.target.value)
})
Would work just as well without hardcoding ids. You could just put the class preserves-old-value on whatever inputs you wanted
https://jsfiddle.net/sgo1qmtu/
Upvotes: 0
Reputation: 113485
A solution is to cache the values in an object. This is the cleanest way I can imagine.
var values = {};
$('#one, #two, #three').change(function(e) {
// Get the text from cache, dynamically
var prevText = values[e.target.id] || "";
// Show something to the user
alert("Modified: " + e.target.value + " | Old: " + prevText);
// Update the text in cache
values[e.target.id] = e.target.value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="one">
<input type="text" id="two">
<input type="text" id="three">
Alternatively, you can store the old value in the element object directly, but I won't recommend to pollute it this way (unless you do it with care):
$('#one, #two, #three').change(function(e) {
var el = e.target;
alert("Modified: " + e.target.value + " | Old: " + (el._old_value || ""));
el._old_value = e.target.value;
});
Upvotes: 2