简体   繁体   中英

jQuery onchange event doesn't change value synchronously

I tried to submit value of 1 input field to other input field in the same form using jQuery synchronously. What I achieved is when the user changes focus from 1st field the value is changed in 2nd field, what I want to achieve is change the value of 2nd field as and when user changes it in the 1st field. Here is my HTML

<div class="form-group">
<label class="form-label">Rate</label>
<div class="form-field">
<input type="text" name="rate_value" id="rate_value">
</div>
</div>

<div class="form-group">
<label class="form-label">Amount</label>
<div class="form-field">
<input type="text" name="amount" id="amount" disabled>
</div>
</div>

and here is my jQuery code

var rate_value;
var amount;
$("#rate_value").on('change', function(){
    amount = $("#rate_value").val();
    $("#amount").val(amount);
});

Use keyup event if you want to update disabled input after each key is pressing

 var rate_value; var amount; $("#rate_value").on('keyup', function() { amount = $("#rate_value").val(); $("#amount").val(amount); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="form-group"> <label class="form-label">Rate</label> <div class="form-field"> <input type="text" name="rate_value" id="rate_value"> </div> </div> <div class="form-group"> <label class="form-label">Amount</label> <div class="form-field"> <input type="text" name="amount" id="amount" disabled> </div> </div> 

Update: you can use input event which is fired when the value of an input or textarea element is changed. It's better than keyup event, it only fires after released the pressed key. input event will fire at the time the value is changed.

 var rate_value; var amount; $("#rate_value").on('input', function() { amount = $("#rate_value").val(); $("#amount").val(amount); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="form-group"> <label class="form-label">Rate</label> <div class="form-field"> <input type="text" name="rate_value" id="rate_value"> </div> </div> <div class="form-group"> <label class="form-label">Amount</label> <div class="form-field"> <input type="text" name="amount" id="amount" disabled> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM