Reputation: 27
What I would like to achieve is using this:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input[name^='audi']").css("background-color", "yellow");});
</script>
</head>
<body>
<input name="audi_a4" type="text" value="3">
<input name="audi_a6" type="text" value="4">
<input name="mercedes" type="text" value="5">
<input name="toyota" type="text" value="2">
<p>
This selector selects all input fields with the attribute name that starts with 'audi'.
</p>
</body>
</html>
Rather than selecting inputs I would like to get a sum of them in another input field (Here the sum should be "7". How can I do this?
Upvotes: 1
Views: 574
Reputation: 1231
You can do like this.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
updatesum();
});
function updatesum(){
sum=0;
$("input[name^='audi']").each(function(){
sum+=Number($(this).val());
});
$("#sumofaudi").val(sum);
}
</script>
</head>
<body>
<input name="audi_a4" type="text" value="3" onchange="updatesum();">
<input name="audi_a6" type="text" value="4" onchange="updatesum();">
SUM of AUDI :<input name="sumofaudi" id="sumofaudi" type="text" value="">
<input name="mercedes" type="text" value="5" onchange="updatesum();">
<input name="toyota" type="text" value="2" onchange="updatesum();">
<p>This selector selects all input fields with the attribute name that starts with 'audi'.</p>
</body>
</html>
Upvotes: 1
Reputation: 2834
iTotal = 0;
$("input[name^='audi']").each(function () {
iTotal += parseInt($(this).val(),10);
});
alert(iTotal)
Upvotes: 0