简体   繁体   中英

how to trigger enter event in text box without pressing enter in javascript

i'm working on computing the product of two textboxes. However, the user needs to press "enter" before the txtTotal will show the total value. Pls I really need help. I'm not really familiar with jquery, and I'm still studying jscript. Thank you so much !

Here is my updated code:

<html>
<head>
<script src="jquery-1.11.2.min.js"></script>
<script>

$('#txtQuantity').bind('input',function(){ 
 var quantity = parseFloat($(this).val()) || 0;
 var amount = parseFloat($('#txtAmount').val());
 var evt = (amount * quantity);
 $('#txttotal').val(evt);
});

</script>
</head>

<body>

<input type="text" class="quan1" name="txtQuantity" id="txtQuantity"/> 
<input type="text"  id="txtAmount" class="quan1" name="txtAmount"   value="4" disabled="" /> 
<input type="text" class="quan1" id="txttotal" name="txttotal"  disabled="" /> <br>

</body>
</html>
var e = $.Event( "keypress", { which: 13 } );
$('#yourInput').trigger(e);

hope this helps

Extra : Read Events and Triggers

if you are using jquery you can do like this.

Solution 1

$('#txtQuantity').on('keypress', function (event) {
       if(event.which === 13){

     var quantity = parseFloat($(this).val()) || 0;
     var amount = parseFloat($('#txtAmount').val());
     var evt = (amount * quantity);
     $('#txttotal').val(evt);
     }
 });

Solution 1 Demo

Solution 2

$('#txtQuantity').bind('input',function(){ 
     var quantity = parseFloat($(this).val()) || 0;
     var amount = parseFloat($('#txtAmount').val());
     var evt = (amount * quantity);
     $('#txttotal').val(evt);
});

Solution 2 Demo

Note: In HTML5 there is a new event, "input", which behaves exactly like you seem to think "change" should have behaved - in that it fires as soon as a key is pressed to enter information into a form. older browsers you can use the "Keyup" event.

If you need to compute the value immediatly whithout the user pressing enter, bind a keyup event to the text box

var compute = function(){
     var quantity = parseFloat($("#txtQuantity" ).val()) || 0;
     var amount = parseFloat($('#txtAmount').val());
     var total = (amount * quantity);
     $('#txttotal').val(total);
}

 $( "#txtQuantity" ).keyup(compute);

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