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>
Related
Below is my javascript function to add new row to <table> in HTML. I need a unique row id for each table row. Below is my code :
$(document).ready(function(){
var html = '<tr><td class="cb"><input class="form-control" type="text" value="" id="inputString" name="inputString"/><div id="showList"><ul class="list-group"></ul></div></td><td><input type="checkbox" name="debit" class="form-control"></td><td><input type="checkbox" name="credit" class="form-control"></td><td><input type="number" name="amount" class="form-control"></td><td><input class="btn btn-warning" type="button" name="remove" id="remove" value="Remove" onclick="removeMe(this);"></td></tr>';
var x=1;
$("#add").click(function(){
$("#table_field").append(html);
});
});
How can I achieve this in the same function
I tried creating unique ids but not able to do.. Please help me
I need a unique row id for each table row.
To add an id to each row while adding you just have to pass it on $("#table_field").append(). Below I am using the length of tr inside #table_field to set an id.
$("#add").click(() => {
const
tTable = $("#table_field"),
tID = `tr${tTable.find('tr').length}`;
tTable.append(
`<tr id = '${tID}'><td>${tID}</td></tr>`
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id = 'table_field'></table>
<button id = 'add'>Add</button>
You can adjust the logic of generating the id to how you see fit. Like using Math.random or Date ticks.
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(){
// ...
});
I'm trying to use the .each() function to capture values from the inputs, however it only works with the inputs present in the DOM.
I am using jQuery to insert more HTML entries. These added inputs are not bound in the DOM, so .on() is used to attach these fields to the DOM.
My goal is to add up all the values of each input added by the user.
Here is an excerpt from the code:
$("form").on("click", "#calc", function () {
var total = 0;
$('#1 .val').each(function(){ /* HERE IS THE PROBLEM */
var valor = Number($(this).val());
if (!isNaN(valor)) total += valor;
});
alert(total);
});
JSBIN for my website
The issue is due to a missing " character delimiting the id you give to the input elements you append, as such the class is lost.
To fix this you can use template literals, which remove the need for spaghetti string concatenation, and also you can remove the id attribute on the dynamic content as it's an anti-pattern. This will leave you with simpler code that's more extensible and far easier to maintain.
Try this:
$(document).ready(function() {
$("form").on("click", ".add-campo", function() {
let $container = $(this).closest('.descricao_rot');
let qtd_input = $container.find('.val').length;
if (qtd_input < 10) {
$container.append(`<br><label for="valor">Valor</label> <input type="number" name="valor[]" placeholder="e aqui..." required="" class="val">`);
} else {
alert("Ainda não é possivel adicionar mais descrições");
}
});
$("form").on("click", "#calc", function() {
var total = 0;
$('.val').each((i, el) => total += Number(el.value) || 0);
alert(total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="add-pub" method="POST">
<div id="formulario">
<br/>
<hr>
<div class="corpo-form" id="corpo1">
<h4>Dia 1</h4>
<br/><br/>
<div class="descricao_rot">
<label for="valor">Valor</label>
<input type="number" name="valor[]" placeholder="e aqui..." required="" class="val">
<button type="button" class="add-campo"> + </button>
</div>
</div>
</div>
<br/><br/>
<div class="botoes">
<button type="button" id="calc"> Calcular </button>
</div>
</form>
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.
I am listing items via table then want to change individual names of items.
<td class="tdFileName">
<?php $nameArray = explode(".", $f->file_name); ?>
<input type="text" name="ra_name" class="raName" value="{{$nameArray[0]}}">
<button type="submit" class="btn-warning btnRaName">Düzenle</button>
</td>
<td>{{$userName}}</td>
$('.btnRaName').on('click', function (e) {
e.preventDefault();
alert($('.raName').val());
location.reload();
});
When I click the individual button I only get first input's value. How can I fix that?
On click you need to pick the prev HTML element as it will be the desired input field:
$('.btnRaName').on('click', function (e) {
e.preventDefault();
var txt = $(this).prev('input.raName').val();
console.log(txt);
location.reload();
});
You need to use DOM traversal to get only the .raName element thats related to the clicked button. Try this:
$('.btnRaName').on('click', function (e) {
e.preventDefault();
var raName = $(this).closest('td').find('.raName').val();
console.log(raName);
});
Select the element relative to your clicked element using sibling()
$('.btnRaName').on('click', function (e) {
e.preventDefault();
var raName = $(this).siblings('.raName').val();
console.log(raName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<td class="tdFileName">
<input type="text" name="ra_name" class="raName" value="the value">
<button type="submit" class="btn-warning btnRaName">Düzenle</button>
</td>
<td class="tdFileName">
<input type="text" name="ra_name" class="raName" value="another value">
<button type="submit" class="btn-warning btnRaName">Düzenle</button>
</td>
</table>