How to sum the value of dynamically created textbox? - javascript

I want to sum the value of dynamically created textbox, but it doesn't work.
$(document).ready(function() {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".code").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".code").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
function addrow() {
$("#customFields").append('<tr><td><input type="text" class="ename" id="name" placeholder="Expense Name"/> </td> <td><input type="text" class="code" id="code" placeholder="Amount"/> </td> </tr>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="customFields">
<tr>
<td>
<input type="button" value="Add" onclick="addrow();" />
</td>
</tr>
</table>

You should use .on() on the table, which allows interaction with new dynamically-created elements. This will allow all keyup from all .code (even those added after page load) to bubble up to #customFields. The rest of your code should not need to be altered.
$(document).ready(function() {
$("#customFields").on( "keyup", ".code", function(){
calculateSum();
});
});
http://api.jquery.com/on/

Please see the
Running Code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".code").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".code").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
function addrow() {
$("#customFields").append('<tr><td><input type="text" class="ename" id="name" placeholder="Expense Name"/> </td> <td><input type="text" class="code" id="code" placeholder="Amount" onKeyUp = "calculateSum()"/> </td> </tr>');
}
</script>
</head>
<body>
<table id="customFields">
<tr>
<td colspan ="2">
<input type="button" value="Add" onclick="addrow();" />
</td>
</tr>
<tr><td><div id="sum">value</div></td></tr>
</table>
</body>
</html>

Related

Numbers Concatenate instead of Adding

I know that + is used for both addition and concatenation, it depends on what the variable type is. I have tried using Number() and parseFloat(), but I can't seem to get them to work. Here is my code:
var grandtotal;
$("#table tr").each(function () {
var row = $(this).closest('tr');
var totalprice = row.find('input[id^="TotalPrice"]').val();
grandtotal += totalprice;
});
$(".total_price").html(grandtotal);
This code gives me an output like this:
NaN1081083936354412531.5105
However, if I add Number() or parseFloat() to the totalprice line like this:
grandtotal += Number(totalprice);
OR
grandtotal += parseFloat(totalprice);
I get nothing returned.
Anybody have any idea what I need to change? Thank you.
EDIT: I have changed the controller code to this:
var grandtotal = 0;
$("#table tr").each(function () {
var row = $(this).closest('tr');
var totalprice = parseFloat(row.find('input[id^="TotalPrice"]').val());
grandtotal += totalprice;
});
$(".total_price").html(grandtotal);
Here is the HTML in question:
<td>
<div class="input-group"> <div class="input-group-addon">$ </div>
<input readonly="readonly" readonly id="TotalPrice{{ $loop->iteration }}" name="TotalPrice[]" placeholder="" class="form-control input-md" step="0.01" type="number" value="{{ $item->TotalPrice }}">
</div>
</td>
I am still getting a blank output.
Making grandtotal to 0 with parseFloat() will solve your problem. You are trying to add tr values to undefined variable.
// give grand total a value
var grandtotal = 0;
$(document).ready(function(){
$("#table tr").each(function () {
var row = $(this).closest('tr');
var totalprice = parseFloat(row.find('input[id^="TotalPrice"]').val());
grandtotal += totalprice;
});
$(".total_price").html(grandtotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
<tr>
<td>
<input type="text" id="TotalPrice" value="1000.50"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="TotalPrice" value="2000"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="TotalPrice" value="10"/>
</td>
</tr>
</table>
<div class="total_price"></div>
Try checking isNaN:
// Inside each
if (totalprice && totalprice.length > 0 && !isNaN(totalprice)) {
grandtotal += parseFloat(totalprice);
}
function getFloat(val) {
if (val && val.length > 0 && !isNaN(val)) {
return parseFloat(val);
}
return null;
}
console.log("getFloat($('#inp1').val()): " + getFloat($('#inp1').val()));
console.log("getFloat($('#inp2').val()): " + getFloat($('#inp2').val()));
console.log("getFloat($('#inp3').val()): " + getFloat($('#inp3').val()));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inp1" type="text" value="" />
<input id="inp2" type="text" value="literal" />
<input id="inp3" type="text" value="100" />

Dblclick listener firing only once in my code

I am new to Javascript and I developed following code which works only once.
function display(arr) {
$(".tbl tbody").empty();
for (i = 0; i < arr.length; i++) {
$(".tbl tbody").append('<tr class="tblrow" id = "'+i+'"> <td><input id="editInput" type="text"/>'+arr[i].Empid+'</td><td>'+arr[i].name+'</td><td>'
+arr[i].pd+'</td><td>'+arr[i].unplannedleaves+'</td><td>'+arr[i].response_time+'</td><td class = "tt"><button class="delbtn" id ="btn'+i+'">Delete</button></td></tr>');
$("td").css("text-align", "center");
$("td").css("border", "1px solid black");
$(".tt").css("border", "none");
$(".tbl").css("border", "none");
$(".delbtn").css("display", "none");
}
}
$("tr").on('dblclick', function() {
var s = this.id;
$("#btn" + s).css("display", "block");
});
$(".delbtn").click(function() {
var s = this.id;
var k = s.slice(3);
arr.splice(k, 1);
display(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="addelem">
<table class="tbl1">
<tr>
<td>
<input id="empid" type="text" placeholder="EmpId">
</td>
<td>
<input id="name" type="text" placeholder="Name">
</td>
<td>
<input id="pd" type="number" placeholder="Pds Delivered">
</td>
<td>
<input id="unp" type="number" placeholder="Unplanned leaves">
</td>
<td>
<input id="rsp" type="number" placeholder="Response Time">
</td>
</tr>
</table>
<button id="submit">Submit</button>
<button id="cancel">Cancel</button>
</div>
After my table gets displayed usingdisplay method. The first time I dblclick a row it works as expected and displays the delete button. I click delete the row gets deleted and the table is re-rendered. However, after this the row is no more dbl-clickable. I tried debugging but the control won't even go in the dblclick listener.
Can someone explain why is it so. Whats going wrong in here?
Bind your tr element like this:
$(document).on('dblclick', "tr", function() {
var s = this.id;
$("#btn" + s).css("display", "block");
});
It will dynamically subscribe any new tr with your dblclick event

JQuery sum using checkbox value and textbox value

How could I get the Final Total based on the sum of a checkbox value and the contents of a textbox?
JSFiddle example
My HTML:
<table border="1">
<tr><td>10<input type="checkbox" class="tot_amount" value="10"></td><td>10<input id="os1" type="text"></td></tr>
<tr><td>20<input type="checkbox" class="tot_amount" value="20"></td><td>20<input id="os2" type="text" ></td></tr>
<tr><td>Total<input type="text" id="total1" readonly></td><td>Total2<input id="total2" type="text" readonly></td></tr>
</table>
Final Total<input type="text" id="final" readonly >
And Javascript:
$(".tot_amount").click(function(event) {
var total = 0;
$(".tot_amount:checked").each(function() {
total += parseInt($(this).val());
});
if (total == 0) {
$('#total1').val('');
}
else {
$('#total1').val(total);
}
});
$('#os1, #os2').on('input',function(){
var os1= parseFloat($('#os1').val()) || 0;
var os2= parseFloat($('#os2').val()) || 0;
$('#total2').val(os1 + os2);
});
Just bind a focus event and do it -
$('#final').bind('focus',function(){
$(this).val(parseInt($('#total1').val())+parseInt($('#total2').val()));
});
LIVE http://jsfiddle.net/mailmerohit5/h43te3z6/

Create ordered list plus generate input field HTML & JS

I have here the complete code of what I have applied and tried. Using the JS below, I got the display of the ordered list wrongly. It must be in 1,2,3 ... (so on and forth). For this, it sticked to 1.,1.,1. .... Another is that, using the JS below, how to customize it that I will get dynamic input fields? Because what if I'll input 5? The result of the fields must be 5 in number also. But what happened, 5 fields are added/appended to the current number of fields (sample, I inputted 3 before and 3 fields displayed so when 5 is inputted, there are 8 fileds in all). What I want is the exact number of fields from the number being inputted. (not that good at JS but I am badly wanting to learn its nature).
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("ul").each(function() {
$(this).find("li").each(function(count) {
$(this)
.css("list-style-type", "none")
.prepend("<div class='listnumber'>" + (count + 1) + ".</div>");
});
});
})
</script>
<script type="text/javascript">
$(document).ready(function() {
$('[name="cand_no"]').on('change', function() {
if (this.value != '') {
var val = parseInt(this.value, 10);
for (var i = 0; i < val; i++) {
var $cloned = $('.template tbody').clone();
$('#studentTable tbody').append($cloned.html());
}
});
})
</script>
</head>
<body>
<p>
<label><strong>No.: </strong></label>
<label><input name="cand_no" type="number" placeholder="Enter no. of fields." /></label>
<div class="clear"></div>
</p>
<div class="cand_fields">
<table id="studentTable" width="630" border="0">
<tr>
<td>Name</td>
</tr>
<tr>
<td><input name="cand_name" type="text" placeholder="Name" required="required" /></td>
</tr>
</table>
</div>
<div class="template" style="display: none">
<table>
<tr >
<td><ul><li><input name="cand_name" type="text" placeholder="Name" required="required" /></li></ul></td>
</tr>
</table>
</div>
</body>
</html>
Thanks a million..
Try
$(document).ready(function () {
$(".template ul li").css("list-style-type", "none").prepend("<div class='listnumber'></div>");
})
$(document).ready(function () {
var $tmpl = $('.template tbody'),
$target = $('#studentTable tbody');
$('[name="cand_no"]').on('change', function () {
if (this.value != '') {
var val = (parseInt(this.value, 10) || 0) + 2;
var len = $target.children().length;
if (val < len) {
$target.children().slice(val).remove();
} else {
for (var i = len; i < val; i++) {
$($tmpl.html()).appendTo($target).find('.listnumber').text(i - 1);
}
}
}
});
})
Demo: Fiddle

Multiply and add values in text area by element in select

Not that easy to explain, so let me paste a little code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
calculateSum();
$(".txt").live("keydown keyup", function() {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
// Iterate through each textboxes and add the values.
$(".txt").each(function() {
// Add only if the value is number.
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
else if (this.value.length != 0){
$(this).css("background-color", "red");
}
});
$("#currentCost").html(sum.toFixed(2));
}
</script>
First off, I'd like to update that code to use the most recent version of jQuery, since it only works with 1.5 I think. (currently, it will just add the values in all textareas and update a span element)
<td>
<select name="struct[213]">
<option selected="selected" value="0"></option>
<option value="2" data-price="4000">A</option>
<option value="3" data-price="6000">B</option>
<option value="4" data-price="8000">C</option>
<option value="7" data-price="15000">D</option>
<option value="11" data-price="80000">E</option>
</select>
</td>
<td>
<input type="text" size="2" maxlength="4" class="txt"
name="numUnits[213]" value="0">
</td>
That's one of the textareas, all follow a similar fashion, and what I'd like to do with them is multiply the data-price in the select by the number entered in the textarea (all textareas and selects have the same [] following the name element), and then I'd like all those products added together in the span #currentCost:
<td class="L1" width="175">
Cost: <span class="redmoney" id="currentCost" name="currentCost">$0</span>
</td>
If that makes any sense...
Try
$(document).ready(function () {
calculateSum();
//register change handler for input and select elements
$(document).on("keyup, change", ".txt, select", function () {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
$(".txt").each(function () {
var value = $.trim(this.value);
if (value.length && !isNaN(value)) {
//find the select in the previous td and multiply the value
sum += parseFloat(value) * ($(this).parent().prev().find('option:selected').data('price') || 0);
//change back the color
$(this).css("background-color", "");
} else if (this.value.length != 0) {
$(this).css("background-color", "red");
}
});
$("#currentCost").html(sum.toFixed(2));
}
Demo: Fiddle

Categories