开发者

jQuery Auto Calculation based on Field

I have this bit of code:

<label>开发者_如何学Python;Number of Shares:</label><input name="shares" id="shares" type="text" />

Total Value: &euro; 0.00

All I need to do is to auto calculate while you type the total value. For example if someone enters 100 in the field, I need to multply it with 1.50 so 0.00 below the field will be replaced with 150.00.

Can someone tell me how can I do this with jQuery?


This is a simple code. I didn't added any the validation or format function

HTML

<label>Number of Shares:</label><input name="shares" id="shares" type="text" />
<br />
Total Value: &euro; <span id="result"></span>

Javascript

$(document).ready(function(){
    $('#shares').keyup(function(){
        $('#result').text($('#shares').val() * 1.5);
    });   
});

Demo: http://jsfiddle.net/7BDwP/


here is a very good calculation plugin for jquery (it helped me) - http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm
it will be usefull link for you


$("#shares").keyup(function() {
   var val = parseFloat($(this).val());
   // If val is a good float, multiply by 1.5, else show an error
   val = (val ? val * 1.5 : "Invalid number");
   $("#result").text(val);
})

And enclose the result in an element

Total Value: &euro; <span id="result">0.00</span>

Using keyup event will make the text be updated in real time.

Demo here.


A very easy approach is to use "keyup".

HTML

<form id="order_form">
<input type="number" id="qty"/>
<input type="text" id="result"/>
</form>

JS

$(document).ready (function(){   
$('#qty').on('keyup change',function(){
    $('#result').val($(this).val() * 1.50);
    });

});

This will change the output in real-time.


// this approach should work...not sure

$("#shares").onchange= update( $(this).val() );

function update(inputVal)
{
 if( parseFloat( inputVal ) == true)
  $("resultDiv").html( inputVal * 1.5 );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜