JavaScript/JQuery: Add Numbers from Fields accounting for Undefined (with 0) -



JavaScript/JQuery: Add Numbers from Fields accounting for Undefined (with 0) -

i have 2 input fields , 3rd 1 called "total". whenever 1 of 2 changes, total has updated sum.

this calculation has take business relationship empty/undefined values. there quick way it? using number(x). take care of unentered values? in case of unentered, 0 should assumed.

$('#field1').on("change", function() { updatetotalcosts(); }); $('#field2').on("change", function() { updatetotalcosts(); }); function updatetotalcosts() { var f1 = $('#field1').val(); var f2 = $('#field2').val(); $('#total').val( number(f1) + number(f2) );

note change event fires after input loses focus. may want utilize input event instead.

to convert string numbers, can utilize unary operator + instead of number.

to default 0 when look falsy, can utilize expr || 0.

class="snippet-code-js lang-js prettyprint-override">var field1 = document.getelementbyid('field1'), field2 = document.getelementbyid('field2'), total = document.getelementbyid('total'); field1.oninput = field2.oninput = function updatetotalcosts() { total.value = (+field1.value || 0) + (+field2.value || 0); }; class="snippet-code-html lang-html prettyprint-override"><input id="field1" /> + <input id="field2" /> = <input id="total" />

or, using jquery,

class="snippet-code-js lang-js prettyprint-override">var $field1 = $('#field1'), $field2 = $('#field2'), $total = $('#total'); $field1.add($field2).on('input change', function updatetotalcosts() { $total.val((+$field1.val() || 0) + (+$field2.val() || 0)); }); class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input id="field1" /> + <input id="field2" /> = <input id="total" />

javascript jquery

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -