Natalia
Natalia

Reputation: 111

Update the value of a field while typing on another field

I would like the field amount to be updated while the user is typing in the field km. I used the .change but the field is only updated when the field loses focus, like the onfocusout event. What coudl I try in order to archive my request?

https://jsfiddle.net/yUhtj/

<label>Expense</label>
    <select id="ExpenseTypeId" name="ExpenseTypeId">
        <option value=""></option>
        <option value="1">Avance sur frais</option>
        <option value="2">Carburant voiture societ&#233;</option>
        <option value="3">Frais kilom&#233;triques</option>
    </select>
    <label id="kmtxt" class="hidden">Distance (the amount will be automatically calculated</label>
    <input type='text' id="km" class="hidden"/>
    <label id="amounttxt" >Amount</label>
    <input type='text' id="amount" />

<script>
    $('#ExpenseTypeId').change(function(){
        var selected_item = $(this).val()
        if(selected_item == "3"){
            $('#kmtxt').val("").removeClass('hidden');
            $('#km').val("").removeClass('hidden');
            $('#amount').prop('readonly', true);
        }else{
            $('#kmtxt').val(selected_item).addClass('hidden');
            $('#km').val(selected_item).addClass('hidden');
        }
    });    

    $("#km").change(function () {

        var price = Number($(this).val());
        var total = (price) * 0.25;
        $("#amount").val(total);
    });
</script>

Upvotes: 1

Views: 2062

Answers (2)

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

Don't use change, use keyboard event instead.

Change your event to keyup

$('"#km"').keyup(function(){
   var price = Number($(this).val());
   var total = (price) * 0.25;
   $("#amount").val(total);
});  

Fiddle

Upvotes: 2

Satpal
Satpal

Reputation: 133403

Use keyup instead of change event with #km element

$("#km").keyup(function () {
    var price = Number($(this).val());
    var total = (price) * 0.25;
    $("#amount").val(total);
});

Upvotes: 7

Related Questions