Hi Guys, today am going to show how you can calculate the sum of numbers in an HTML text field mixed with symbols, let’s just say in this scenario you have an HTML text field which contains numbers separated by symbols for instance a dash (-) after some counted numbers for example 10-53-63-45 and you would just like to compute all the four numbers together without considering the fact that they are separated with this (-) symbols. do not fear anything because there is surely a way to deal with the situation.
the javascript code below is ideal to do that for you.
1 2 3 4 5 6 7 8 9 10 11 |
function add(string){ return string.split('-').reduce(function(a,b){return+a+(+b); }); } jQuery(document).ready(function($){ $('#Your_Input_Field_Key').change(function(){ var val1 = $("#Your_Input_Field_Key").val(); result = add(val1); $("#Your_Result_Field_Key").val(result); }); }); |
the Jsfidle bellow will show the live usage of the code presented above
in case you want to use any other way with your HTML elements you can replace $("#Your_Result_Field_Key").val(result);
with document.getElementById('Your_Result_Field_Key').value = result;
it also works perfectly
Leave a comment