Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  91] [ 2]  / answers: 1 / hits: 6925  / 10 Years ago, wed, march 12, 2014, 12:00:00

I don't usually use js, so am hoping for a quick win. Although I can't find the answer on SO in spite of quite a few similar questions out there.



I have a form...



<input type=text size=5 id=value1 name=value1 />
<input type=text size=5 id=value2 name=value2 />

<input type=text size=5 id=total readonly=readonly class=bckground name=total />


How can I use ajax (or otherwise) to multiply value1 by value2 after their inputs have been entered, but before the form is submitted?



Requirement is to simply display a product of value1 * value 2 as the form is being filled out. But it would be nice to embed it to the form field, as above, in case I want to add it to my database.



Edit: Below is my attempt. But I can only get a span element to update, and not automatically. Also it fails if the fields are blank.



<script>
function calculateSum()
{
value1 = parseInt(document.getElementById(value1).value);
value2 = parseInt(document.getElementById(value2).value);

sum = value1 * value2;

document.getElementById(totalpledge).innerHTML = sum;
}
</script>


Seems to work with a button...



<input type=text size=5 id=value1 name=value1 />
<input type=text size=5 id=value2 name=value2 />

<span id=totalpledge>--</span>
<span><button onclick=calculateSum()>Submit!</button></span>

More From » jquery

 Answers
5

I'd do something like this:



HTML



<input type=text size=5 id=value1 name=value1 class=value/>
<input type=text size=5 id=value2 name=value2 class=value/>

<input type=text size=5 id=total readonly=readonly class=bckground name=total />


Just added class=value to the elements so you can easily identify all of the ones that need to contribute to the total.



jQuery:



jQuery(document).ready(function($) {
var $total = $('#total'),
$value = $('.value');
$value.on('input', function(e) {
var total = 1;
$value.each(function(index, elem) {
if(!Number.isNaN(parseInt(this.value, 10)))
total = total * parseInt(this.value, 10);
});
$total.val(total);
});
});


That binds an event handler to all of the .value elements (all of the elements with class=value) for the input event, which fires whenever the value of the input changes. Then it simply iterates through each of the required inputs and multiplies their values together. Finally it puts that total value into the #total element.



jsFiddle demo


[#46941] Tuesday, March 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lonnier

Total Points: 621
Total Questions: 113
Total Answers: 98

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
;