I’m trying to add these two or more inputs in jquery, to give me the output of both input values (5 + 2) times a “product” amount ($50.25).
How can I add all inputs, without assigning any class or id to these inputs?
Can you please guide me here.
<input type="text" value="5" /> <input type="text" value="2" />
<h3></h3>
<script>
$("input").keyup(function () {
var value = parseFloat($(this).val());
var item_price = parseFloat("50.25");
$("h3").text(value * item_price);
}).keyup();
</script>
This code outputs the most recent edited field. For example, if I were to switch the first field to a value of 2 the total will change to “100.5”, then changing the other field will change the total based on That field, not both.
I tried inserting the key listener into $(“input”).each() selector, but obviously something snapped in the code, since it didn’t return any results.
$("input").each(function() {
value += parseFloat($(this).val());
$("input").keyup(function () {
var value = parseFloat($(this).val());
var item_price = parseFloat("50.25");
$("h3").text(value * item_price);
}).keyup();
});
This appears to be what you’re looking for. Put all of the calculations in a function, and just bind that function to the keypress. You’ll also probably want to call that function right away to do initial calculations as I have done in my demo.
See Live Demo: http://jsfiddle.net/za2vJ/4/