Can't get values of input with js - javascript

I have a inputs in loop using thymeleaf, I need when hover each iteration get the value and calculate sum
<tr th:each="person : ${persons}">
<td th:text="${person.first_name}"></td>
<td th:text="${person.last_name}"></td>
<td th:text="${person.phone}"></td>
<td><input id="age" class="form-control"
type="text" name="age" th:field="*{ages}">
</td>
</tr>
Total : <input type="text" name="sum" id="sum"/>
My js script :
<script type="text/javascript">
$(document).ready(function(){
$("#age").each(function() {
$(this).on('input', function(){
calculateSum();
});
console.log("sum :"+sum);
});
});
function calculateSum() {
var sum = 0;
$("#age").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(2));
}
</script>
My code give me on total only the first value (like it doesnt work on 2nd iteration), i dont know why !!

Ids should be unique on a page; as such, id selectors usually only return the first element with that id. You should use classes instead.
<input class="age" class="form-control" type="text" name="age">
Your selectors should then become:
$(".age").each(function(){
// ...
});

Related

How to get the value of Input type number inside a table

I have a table with several rows in which one of the cells has an imput type = number. I want to go through all the rows and get the number that is in that cell. I'm really lost on how to do it.
<tr class="iterate">
<td class="cantidad"> <input type="number"
onchange="actualizar()" name="cantidad" placeholder="0" min="0" max="99"></td>
</tr>
function actualizar(){
var total=0;
$("tr.iterate").each(function() {
var quantity1 = $(this).find(".cantidad").innerHTML,
alert(quantity1);
});
}
I tried with innerHTML, value, text() and with none of them working.
.cantidad is the td element not the input you are looking for. You have to find the input inside the .cantidad.
Also I will prefer oninput event instead of onchange:
$(this).find(".cantidad input").val()
function actualizar(){
var total=0;
$("tr.iterate").each(function() {
var quantity1 = $(this).find(".cantidad input").val();
alert(quantity1);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr class="iterate">
<td class="cantidad"> <input type="number"
oninput="actualizar()" name="cantidad" placeholder="0" min="0" max="99"></td>
</tr>
</table>
Please Note: innerHTML and value used when using vaniall JS, you can not use them on jQuery referenced element.

Output sum of inputs with same class to a span

I have a series of subtotal boxes which output the value of a quantity multiplied by a unit price, and I need the values of each of these to be added together and output to a span further down in a form.
I've had a go at this using previously-suggested methods, but can't get it to work. Any ideas why?
HTML:
<button id="addItem" href="#">Add Item</button> <!-- Trigger button -->
<td><input name="subtotal" class="sinput txt"></td> <!-- Subtotals to add -->
<span id="totalplus" class="totalsub"></span> <!-- Output total -->
JS:
$('#invoiceItemForm button#addItem').click(function(e) {
e.preventDefault();
var sum = 0;
$('.invoicemade .sinput').each(function() {
sum += +$(this).val();
});
$('.invoicemade span#totalplus').val(sum);
});
Try the below snippet:
$('button#addItem').click(function(e) {
e.preventDefault();
var sum = 0;
$('.sinput.txt').each(function() {
sum += parseInt($(this).val()); //Change the calculation acc. to your needs
});
$('span#totalplus').html(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="addItem" href="#">Add Item</button> <!-- Trigger button -->
<td><input name="subtotal" class="sinput txt"><input name="subtotal" class="sinput txt"><input name="subtotal" class="sinput txt"></td> <!-- Subtotals to add -->
<span id="totalplus" class="totalsub"></span>
Removed #invoiceItemForm because you did not give that code.
You should use .html() instead of .val() on span because it is not a form control
Note Add #invoiceItemForm when using this code in your program.
Use parseInt for calculation to avoid string concat. Other code error are in comment.
$('button#addItem').click(function(e) {
e.preventDefault();
var sum = 0;
$('.sinput').each(function() {
sum += parseInt($(this).val()); // Remove +
});
alert(sum);
$('#totalplus').text(sum); // Remove quote
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>
<tr>
<td><input name="subtotal" class="sinput txt"></td>
<td><input name="subtotal" class="sinput txt"></td>
</tr>
<span id="totalplus" class="totalsub"></span>
<button id="addItem" href="#">Add Item</button>

Grid with multiple input fields per row

I have a "grid" with several input fields per row. Lets say each input field represents a day of the week.
html:
<table id="grid">
<tr>
<td><input class="fri" type="text" value="foo" /></td>
<td><input class="mon" type="text" value="bar" /></td>
<td><input class="tue" type="text" value="baz" /></td>
<td><input class="wed" type="text" value="x" /></td>
<td><input class="thu" type="text" value="y" /></td>
</tr>
...
jQuery:
$('#grid').on('change', '.fri', function () {
var value = $(this).val();
//do something
});
$('#grid').on('change', '.mon', function () {
var value = $(this).val();
//do something
});
// And so on...
There can be any number of rows, all having the same fields.
I made a working fiddle of what I am trying to do.
However, I feel I am repeating myself a little too much (with the jQuery) and I was wondering if there is a way to do the above more concisely (preferably using jQuery).
You can rather use element selector instead of using individual IDs and then binding them:
$('#grid').on('change', 'input:text', function () {
var value = $(this).val();
//do something
});
Also if you have other textboxes in same table which you don't want to target then use multiple class selector:
$('#grid').on('change', '.fri,.mon,.tue', function () {
var value = $(this).val();
//do something
});
You could use event.target like this:
$('#grid').on('change', function (e) {
alert(e.target.value);
});
This would be the only jQuery you need.

Jquery .change() only updates results one time

I have 3 input fields. #first, #second, and #third, as well as a fourth field #theResult.
<div id="addFields">
<span id="addFieldsHeader">Add The Fields</span>
<table style="margin:0 auto;">
<tr>
<td style="width:80px;">First
<input id="first" size="5" value="3" name="first" style="width:75px" />
</td>
<td style="width:80px;">Second
<input id="second" size="5" value="5" name="second" style="width:75px" />
</td>
<td style="width:80px;">Third
<input id="third" size="6" maxlength="7" name="third" style="width:75px" value="0" />
</td>
<td style="width:80px;">Result
<input id="theResult" size="7" maxlength="7" name="result" style="width:75px" value="0" />
</td>
</tr>
</table>
</div>
I have tried to write a jQuery script that will add the values of #first, #second, and #third together and display the results in #theResult.
I did find docs for the .change() function here which looked like it would suit my needs better than .blur() or .keyup(), as I want the value of #theResult to update each time the value of #first, #second, or #third is changed by the user.
I have the following jQuery:
$(document).ready(function () {
var first = parseInt($("#first").val(), 10);
var second = parseInt($("#second").val(), 10);
var third = parseInt($("#third").val(), 10);
var theResult = first + second + third;
$("#addFields input").change(function () {
$("#theResult").val(theResult);
});
});
When I change a value in any of the inputs #theResult does update, but it only works once and after that I have to reload the page again to get it to work. Also, only the initial values are added, not the updated values. Fiddle is here
Anyone with experience I greatly appreciate your help :)
$(document).ready(function() {
$("#addFields input").change(function() {
var first = parseInt($("#first").val(),10);
var second = parseInt($("#second").val(),10);
var third = parseInt($("#third").val(),10);
var theResult = first + second + third;
$("#theResult").val(theResult);
});
});
You just have to move the variables inside the change() function, so it updates each time.
JSFiddle
You Only need to bring you variables in the change function
$("#addFields input" ).change(function() {
var first = parseInt($("#first").val(),10);
var second = parseInt($("#second").val(),10);
var third = parseInt($("#third").val(),10);
var theResult = first + second + third;
$("#theResult").val(theResult);
});
it because the new value is not assigned to those variables
Try like this:
$(function() {
$("#addFields input" ).change(function() {
var first = parseInt($("#first").val(),10);
var second = parseInt($("#second").val(),10);
var third = parseInt($("#third").val(),10);
var theResult = first + second + third;
$("#theResult").val(theResult);
});
});

jquery multiply 2 textboxs then show the solution

I have this code that is not working. I am trying to multiply 2 textboxs and show the solution, but it doesn't show anything when I click. The code I have so far is this... what can be wrong with the code below?
<script type="text/javascript">
$('#AddProduct').click(function() {
var totalPrice = $('#debt').val() * $('#income').val();
$('#solution').val() = totalPrice;
});
</script>
<form name="form" method="post" action="">
<table>
<tr>
<td><input type="text" name="income" id="income" /></td>
<td><input type="text" name="debt" id="debt" /></td>
<td><input type="text" id="solution" name="solution" /> </td>
</tr>
</table>
</form>
Your jQuery needs to be:
$('#AddProduct').click(function() {
var totalPrice = parseInt($('#debt').val()) * parseInt($('#income').val()); // you can't multiply strings
$('#solution').val(totalPrice); // This is how you use .val() to set the value.
});
This is the way that you'd set the value of the solution textbox:
$('#solution').val(totalPrice);
Also, do you actually have an element with an id of 'AddProduct' on your page?
var totalPrice = $('#debt').val() * $('#income').val();
$('#solution').val(totalPrice);
Demo
After, you add jquery to your page as below
<script src="http://code.jquery.com/jquery-latest.js"></script>
you can do the following:
$('#AddProduct').click(function() {
var totalPrice = parseInt($('#debt').val(),10) * parseInt($('#income').val(),10);
$('#solution').val(totalPrice);
});
You have to tell it you want the value of the input you are targeting.
And also, always provide the second argument (radix) to parseInt. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.
Providing 10 assumes you are wanting a base 10 number.

Categories

Resources