Reputation: 568
I have a strange behavior with the "keyup" event: When i fill out an input field with something, then i delete the value, the last delete keyup event isn't recognised.
Example code:
$('#input').on('keyup',function(){
if($(this).val().length > 0){
$('#text').html($(this).val())
}
});
Fiddle HERE
Any solution or why this strange behavior?
Upvotes: 0
Views: 1561
Reputation: 42054
UPDATE
According to the new problem described in the fiddle the solution can be based on jQuery data:
$(function () {
$('#input-deposit').on('keyup', function (e) {
if ($(this).val().length >= 0) {
$('#text').html($(this).val())
}
});
// set the default of previousValue
$('#input-deposit').data('previousValue', 0);
$('#input-deposit').on('keyup', function (e) {
var t = 2000;
if (!isNaN(this.value) && this.value.length != 0) {
// get the previous value
var previousValue = parseFloat($('#input-deposit').data('previousValue'));
var total = parseFloat($('#input-balance').val());
var deposit = parseFloat($(this).val());
$('#input-deposit').data('previousValue', deposit);
// use previousValue
t = total + previousValue - deposit;
} else {
// reset previousValue
$('#input-deposit').data('previousValue', 0);
}
$('#input-balance').val(t.toFixed(2));
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<label>Deposit</label>
<input type="text" value="" id="input-deposit"/>
<label>Balance</label>
<input type="text" value="2000" id="input-balance"/>
<div id="text"></div>
The problem is:
if($(this).val().length > 0){
This must be:
if($(this).val().length >= 0){
Snippet:
$(function () {
$('#input').on('keyup',function(){
if($(this).val().length >= 0){
$('#text').html($(this).val())
}
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" value="" id="input"/>
<div id="text"></div>
Upvotes: 0
Reputation: 8537
Just change the comparator to >=
instead of >
and it works.
$('#input').on('keyup',function(){
if($(this).val().length >= 0){
$('#text').html($(this).val())
}
});
Upvotes: 1