开发者

Add values of textfields Jquery HTML

开发者 https://www.devze.com 2023-04-13 02:36 出处:网络
I have a textfield and I need to add their values. The problem is that the values in these textfields are not typed in but got from another source. These text fields also happen to be read only.

I have a textfield and I need to add their values. The problem is that the values in these textfields are not typed in but got from another source. These text fields also happen to be read only. What I need is the appropriate event to fire when the values of these textfields change. Here is what i am currently using but its not good enough since I have to click and lose focus so that the textfields calculate. FYI .change and .click events don't work well either. I need the values summed up immediately they change dynamically. #grandmealstotal is one of the textfields that needs to be added, #usdgrandaccomtotal is the other textfield that needs to be added. results are alerted out and displayed in a textfield with id #gross_tripexpense. Below is what I'm using

$("#grandmealstotal").live('blur',function(){
var mealtotal=parseFloat($("#grandmealstotal").val());
var accomtotal=parseFloat($("#usdgrandaccomtotal").val());
var grosstotals=parseFloat(accomtotal+mealtotal);
alert(grosstotals)
$("#gross_tripexpense").val((grosstotals).toFixe开发者_如何学God(2));
})

Any help appreciated.


You could use the .keydown() or .keyup() event in this case:

$('#grandmealstotal').keyup(function() {
    var mealtotal = parseFloat($('#grandmealstotal').val());
    var accomtotal = parseFloat($('#usdgrandaccomtotal').val());
    var grosstotals = parseFloat(accomtotal + mealtotal);
    alert(grosstotals);
    $('#gross_tripexpense').val((grosstotals).toFixed(2));
});

Also make sure that you perform error handling as those parseFloat methods could fail if the user enters invalid numbers. You could use the isNaN function for this:

var mealtotal = parseFloat($('#grandmealstotal').val());
if (!isNaN(mealtotal)) {
    // use the mealtotal variable here
} else {
    alert('please enter a valid number for total meals');
}

UPDATE:

If the values are readonly and cannot change you could perform the calculation once the DOM is ready:

$(function() {
    ... do the calculation here
});


You could add an event handler for .change() event and then trigger the .change() event every time you update the values in your input.

0

精彩评论

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

关注公众号