I want to SUM the price of all dynamically created rows and display into total input field..I have tried some things but not working for me.I have posted my script and image that explains how it should works. Everything is working and saving in database just want total amount of all items. Please see image for clear concept. Total of 1st row is saving in total but not working for dynamically created rows.
Image:
It should work like this
Html:
<div class="form-group">
<label>Total</label>
<input readonly type="text" id="total_amount" class="form-control"
name="total_amount">
</div>
Script:
<script>
var counterr = 1;
$(document).ready(function () {
$('#unit_price,#item_quantity').change(function () {
// alert();
var unitPrice = $('#unit_price').val();
// console.log(unitPrice);
var quantity = $('#item_quantity').val();
// console.log(quantity);
var total = (unitPrice * quantity).toFixed(0);
$('#total_price').val(total);
$('#total_amount').val(total);
});
// Input Fields
var maxField = 100; //Input fields increment limitation
var addButton = $('#add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
$(addButton).click(function (e) {
e.preventDefault();
counterr++;
//Check maximum number of input fields
if (counterr < maxField) {
fieldHTML = makeNewRow(counterr);
$(wrapper).append(fieldHTML); //Add field html
// $('#department-'+counterr).select2();
// console.log("Unit price", counterr);
$('.unit_price' + counterr).change(function () {
// console.log("hello");
var unitPrice = $('.unit_price' + counterr).val();
// console.log(unitPrice);
var quantity = $('#item_quantity' + counterr).val();
// console.log(quantity);
var total = (unitPrice * quantity).toFixed(0);
$('#total_price' + counterr).val(total);
$('#total_price').each(function() {
subtotal += parseFloat($(this).val());
console.log('test',subtotal);
});
$('#total_amount').val(subtotal);
});
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('#newrow').remove(); //Remove field html
counterr = counterr--; //Decrement field counter
})
});
function makeNewRow(counterr) {
return '<div class="row" id="newrow">' +
'<div class="col-md-4">' +
'<div class="form-group">' +
'<select onChange="getPurchasePrice(this.value);" style="background-color: #f5f6f9" id="item_name' + counterr + '" class="form-control dep"' +
'placeholder="Enter Item" name="testing[]"' + '>' +
'<option value = "">Select Item</option>' + '>' +
'#foreach($items as $item)' + '>' +
'<option value = "{{$item->id}}">{{$item->item_name}}</option>' + '>' +
'#endforeach' + '>' +
'</select>' +
'</div>' +
'</div>' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<input style="background-color: #f5f6f9" type="number" id="item_quantity' + counterr + '" class="form-control"' +
'placeholder="Enter.." name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<input style="background-color: #f5f6f9" type="number" id="unit_price' + counterr + '" class="unit_price' + counterr + ' form-control"' +
'placeholder="Enter.." name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<div class="col-md-3">' +
'<div class="form-group">' +
'<input value="0" style="background-color: #f5f6f9" disabled type="text" id="total_price' + counterr + '" class="form-control"' +
'placeholder="Total" name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<a style="height:40px;margin-left:25px" href="javascript:void(0);" class="btn btn-danger remove_button">X</a>' +
'</div>'; //New input field html
}
/*function removeDiv(no){
$("#testingrow-"+no).remove();
x--;
}*/
</script>
Add a function to recalculate the grand total 'recalcGrandTotal'
var recalcGrandTotal = function() {
var grandTotal = 0; // Declare a var to hold the grand total
$("[id^=total_price]").each(function() { // Find all elements with an id that starts with 'total_price'
grandTotal += parseInt($(this).val()); // Add the value of the 'total_price*' field to the grand total
})
$('#total_amount').val(grandTotal); // append grand total amount to the total field
}
Then, hook this function up to the 'total price' recalculation function:
Find
$('#total_price' + counterr).val(total);
Add after:
recalcGrandTotal();
To substract from grand total upon removal of an item, hook this function up to the item removal function. Find:
counterr = counterr--; //Decrement field counter
Add after:
recalcGrandTotal();
Related
Below is my code which works this way. when user selects checkbox, it appends the selected item name and price and calculates the sub total based on the quantity the user types in.
Now when a user deselects a checkbox, the item deselected disappears and the total reduces the total to the old total (previous total).
What I want to achieve is, my html below I can icon fa fa-close which I want it to perform like how when a checkbox is deselected. So when a user clicks on the icon, it removes the respective item and also reduces the total to the old total
function order(food) {
var ad = JSON.parse(food.dataset.food),
existing;
if (food.checked == true) {
$('.panel').append(
'<div class="container" style=" font-size:14px; "> ' +
'<input type="hidden" value=' + ad.id + ' data-id="' + ad.id + '" name="food_id[]" />' +
'<table style="width:100%;" class="table" id="tables">' +
'<thead>' +
'<thead>' +
'<tbody id="item_list">' +
'<tr>' +
'<td class="icon" ><i class="fa fa-close"></i></td>' +
'<td class="name" >' + ad.name + '</td>' +
'<td class="price" data-price="' + ad.price + '">' + ad.price + '</td>' +
'<td><p class="total" ><span class="line-total" name="total" id="total"></span></p></td>' +
'</tr>' +
'</tbody>' +
'</table>' +
'</div>'
)
}
} else {
var total = $(".panel .container [data-id=" + ad.id + "]").parent().find(".total").text();
$(".panel .container [data-id=" + ad.id + "]").parent().remove();
if (total) {
$('.checkout span').text(function(index, oldtext) {
console.log('this is my old text ' + oldtext)
return oldtext ? oldtext - total : oldtext;
});
}
}
$('.panel').on('keyup', '.quantity', function() {
order_container = $(this).closest('div');
quantity = Number($(this).val());
price = Number($(this).closest('div').find('.price').data('price'));
points = Number($(this).closest('div').find('.points').data('points'));
order_container.find(".total span").text(quantity * price);
order_container.find(".pts-total span").text(quantity * points);
sum = 0;
points = 0;
$(".line-total").each(function() {
sum = sum + Number($(this).text());
})
$(".pts-total").each(function() {
points = points + Number($(this).text());
})
$('.checkout span').text(sum);
});
You can try this simple click event
$('.panel').on('click','.fa.fa-close',function(){
$(this).closest('.container').remove();//remove the current element
var sum = 0;
$(".line-total").each(function(){
sum = sum + Number($(this).text());
});//calculate the new sum
$('.checkout span').text(sum);
})
I would like to select the content of this element
<div class="entry-content">
comment.body +
</div>
I want to get that comment.body in the function I call below, more precisely in
var body = parent.find('entry-content');
How can I select the content of a certain div? I tried val() and contents() and none of them worked.
Any suggestion?
$("body").on("click", ".show-textarea", function(){
var answerid = $(this).data('answer');
var type = $(this).data('type');
var questionid = $(this).data('question');
var $commentForm = $(this).parent().find('.comment-form').first();
console.log(answerid);
$.getJSON("/controller/api/comments/comment.php", {
answerid : answerid,
questionid : questionid,
type : type
}, function (data) {
$commentForm.find('article').remove();
console.log("AID " + answerid);
console.log("Data" + data.length);
$.each(data, function(i, comment) {
console.log("Comment:" + comment);
$commentForm.append('<article class="tweet-data">' +
'<div class="comment-items">' +
'<div class="qa-c-list-item hentry comment" id="c3574">' +
'<div class="asker-avatar">' +
'<a>' +
'<img width="40" height="40" src="' +
comment.user_photo +
'"></a>' +
'</div>' +
'<div class="qa-c-wrap">' +
'<div class="post-button">' +
'<button name="" onclick="" class="btn icon-flag" title="Flag this comment as spam or inappropriate" type="submit">flag</button>' +
'<button name="" class="btn icon-answers" title="Reply to this comment" type="submit">reply</button>' +
'</div>' +
'<span class="qa-c-item-meta">' +
'commented' +
' 1 day' +
' ago' +
' by ' +
'<a style="display: inline" href="" class="qa-user-link url nickname">' +
comment.username +
'</a> ' +
'<span class="qa-c-item-who-points"> ' +
'<span class="qa-c-item-who-points-pad">(</span><span class="qa-c-item-who-points-data">140</span><span class="qa-c-item-who-points-pad"> points)</span> ' +
'</span> ' +
'</span> ' +
'</span> ' +
'<div class="qa-c-item-content" style="color: #2d2727; font-size: 13px"> ' +
'<a name="3574"></a>' +
'<div class="entry-content">' +
comment.body +
'</div> ' +
'</div> ' +
'<div class="comment-edit-form">' +
'<form method="post" action="/controller/actions/comments/edit_comment.php">' +
'<button class = "edit-comment btn {if !$isMine}hidden{/if}" type="button">Edit</button>' +
'</form>' +
'</div> ' +
'</div> <!-- END qa-c-item --> ' +
'</div>' +
'</div></article>');
});
});
$commentForm.show();
});
$("body").on("click", ".textarea-ok, .textarea-cancel", function(){
commentsFetched = false;
$('.comment-form').hide();
});
$("body").on("click", ".edit-comment", function(){
console.log("Hello");
var parent = $("body").find('article').last();
var body = parent.find('entry-content');
console.log(body);
var parent_parent = $("body").find('article').parent().last();
parent.remove();
console.log(parent);
var button = $(this),
commentField = $('<div class="comment-form">' +
'<form method="post" action="/controller/actions/comments/edit_comment.php">' +
'<textarea name="comment" rows="4" cols="40" class="qa-form-tall-text">' +
body +
'</textarea>' +
'<input type="hidden" name="answerid" value="" />' +
'<input type="hidden" name="questionid" value="" />' +
'<button type="submit" class="textarea-ok">Edit Comment</button>' +
'</form>' +
'</div>'); // create a textarea element
commentField
// set the textarea's value to be the saved content, or a default if there is no saved content
.val(button.data('textContent') || 'This is my comment field\'s text')
// set up a keypress handler on the textarea
.keypress(function(e) {
if (e.which === 13) { // if it's the enter button
e.preventDefault(); // ignore the line break
button.data('textContent', this.value); // save the content to the button
$(this).remove(); // remove the textarea
}
}).appendTo(parent_parent); // add the textarea to the document
});
Since the binding is on '.edit-comment' which is a child of the '.tweet-data' encapsulating each individual entry (from the looks of your logic) I would suggest doing
$(this).closest('.tweet-data').find('.entry-content').text();
Your current logic is going to the last article for the 'parent' element. So if you tried to click the edit comment option on a tweet data other than the last one, your logic will most likely not work. Doing the lookup contextually by which element was clicked will fix this potential issue.
Hi people i have a dynamic table (add rows from ajax requests) and i need sum and multiply values always (without a trigger event).
i have already a functions that make it with the event (blur) but i don't wanna make it by using the blur trigger.
There is a way for do it?
My code:
$.fn.sumValues = function() {
var sum = 0;
this.each(function() {
if ($(this).is(':input')) {
var val = $(this).val();
} else {
var val = $(this).text();
}
sum += parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10);
});
return sum;
};
function totaliza() {
var total_recep = $('input[name^="costot"]').sumValues();
$('#total_art').val(total_recep);
}
var counter = 0;
$(document).on('click', '#bt_add', function(e) {
counter++;
var tr = '<tr id="art_' + counter + '">';
tr = tr + '<td><button name="del_art' + counter + '" id="del_art' + counter + '" class="btn btn-default btn-xs del_art" type="button">DEL</button></td>';
tr = tr + '<td><input name="cbarra' + counter + '" id="cbarra' + counter + '" class="form-control" value="02020202" readonly></td>';
tr = tr + '<td><input name="art' + counter + '" id="art' + counter + '" class="form-control" value="ARTICULO" readonly></td>';
tr = tr + '<td><select name="und' + counter + '" id="und' + counter + '" class="form-control list"></select></td>';
tr = tr + '<td><input name="cal' + counter + '" id="cant' + counter + '" class="form-control numeric cal" value="0"></td>';
tr = tr + '<td><input name="cal' + counter + '" id="costou' + counter + '" class="form-control numeric cal" value="0"></td>';
tr = tr + '<td><input name="costot' + counter + '" id="costot' + counter + '" class="form-control cal" readonly value="0"></td>';
tr = tr + '</tr>';
$("#inv_recep_det tbody").append(tr);
$('.form-control').change(function() {
var number = this.name.replace('cal', '');
var costot = ($('#cant' + number).val() * $('#costou' + number).val())
$('input[name^="costot' + number + '"]').val(costot);
totaliza();
});
$('.del_art').click(function() {
var number = this.name.replace('del_art', '');
$('#art_' + number).remove();
totaliza();
});
});
https://jsfiddle.net/JuJoGuAl/kpLs9zcg/
Something like that?
http://jsfiddle.net/JuJoGuAl/0vx64u2y/
Rather than continuing in comments, I thought an answer might be of better use. Currently, you use:
$(".form-control).change(...)
to trigger the update. Some browsers may force you to lose the focus on an element to actually trigger that. Instead, change that line to:
$(".form-control").on("input", function(){ ... })
This has been discussed here: What is the difference between "change" and "input" event for an INPUT element
Other than that, I've made no changes to your fiddle: https://jsfiddle.net/snowMonkey/kpLs9zcg/5/
See below code. I am creating 2 text fields at a time. Now how could I type on one text field and make the other twin text field have the same values simultaneously?
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
<script>
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..."/>' + '<br>' + '</div>' + '</div>');
$(OuterWrapper).append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '">' + '</div>');
x++;
return false;
});
});
</script>
I created a fiddle that I think does what you want: http://jsfiddle.net/3h1h5j7y/
Here is the code.
HTML
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
JavaScript
I added a data- attribute to the inputs with the tfCont id so that they can operate in pairs as they are added.
Also, I am using the on() method so that objects can be added dynamically. It is filtering on the fTypex class.
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..." data-tfcount="' + tfCont + '"/>' + '<br>' + '</div>' + '</div>');
$("#OuterWrapper").append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '" data-tfcount="' + tfCont + '">' + '</div>');
x++;
return false;
});
$(document).on("click blur keyup", "input.fTypex", function() {
var tfc = $(this).data("tfcount");
$("#tf_" + tfc).val(this.value);
});
});
I had to change $(OuterWrapper) from your example to $("#OuterWrapper") because there was not a variable.
Try something like this :
use onkeyup to call a function which binds the values
HTML
<body>
<input id='ip1' onkeyup='updateOther(this);' type='text'>
<input id='ip2' type='text'>
<script src="script.js"></script>
</body>
JS:
function updateOther(obj){
$('#ip2').val($(obj).val()) ;
}
http://plnkr.co/edit/dpwav5fGcisZcjBIzYyz?p=preview
I am dynamically adding and removing textboxes though I can successfully adds textbox but unable to remove textbox on clicking the remove button every time i have to reload the browser to remove the textboxes after clicking remove button.
here is my javascript for adding and removing textboxes.
<script type="text/javascript">
$(document).ready(function(){
var COUNTER = 3;
var labelArray = ["answer", "rank"];
$("#addButton").click(function () {
for(var i = 0; i < labelArray.length; i++){
createNewInput(labelArray[i]);
}
COUNTER++;
});
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#TextBoxesGroup" +COUNTER).remove();
});
});
</script>
here is my html for textboxes.
<div id="TextBoxesGroup">
<div class="control-group">
<label class="control-label">answer_1: </label>
<div class="controls">
<input type="text" name="answer_1" id="answer_1" required="true" >
</div>
</div>
<div class="control-group">
<label class="control-label" for="rank1">Rank 1</label>
<div class="controls">
<input type="text" name="rank_1" id="rank_1" required="true">
</div>
</div>
<div class="control-group">
<label class="control-label">answer_2: </label>
<div class="controls">
<input type="text" name="answer_2" id="answer_2" required="true" >
<button class="btn btn-mini btn-danger" data-toggle="button" type="button" id="removeButton">
-
</button>
<button class="btn btn-mini btn-success" data-toggle="button" type="button" id="addButton">
+
</button>
</div>
</div>
<div class="control-group">
<label class="control-label" for="rank1" required="true">Rank 2</label>
<div class="controls">
<input type="text" name="rank_2" id="rank_2" required="true">
</div>
</div>
</div>
can anyone what's wrong in it so that I am unable to remove textboxes on clicking the button ? Thanks
you need to modify 2 things here:
1- when appending the new elements, mark their holding div with the current COUNTER value at the end, so it's easy to target them later (like on step 2 below).
so adding new elements should be like this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group'+COUNTER+'">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
...
...
instead of this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
2- when removing elements, we will target those with the current COUNTER value at the end of their class name,this way you will remove the last group, and still check if the groups are 3 or lower, no removal should happen.
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$(".control-group"+COUNTER).remove();
});
});
Update: check my updated fiddle http://jsfiddle.net/qqqyC/1/
note: considering that we are appending the COUNTER value at the end of the class name. if class is giving you any styles it will not work. in this case you should not use class name as the target property and consider marking the new group using another attribute/property, and target this attribute/property when removing your elements.
Use .on as you want to bind $("#removeButton").click(function () { to dynamically added elements. It should be
$("#removeButton").on("click", function () {
//.....
});
$(document).ready(function(){
var COUNTER = 3;
var labelArray = ["answer", "rank"];
$("#addButton").click(function () {
for(var i = 0; i < labelArray.length; i++){
createNewInput(labelArray[i]);
}
COUNTER++;
});
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#answer_" +COUNTER).parent('div').parent('div').remove();
$("#rank_" +COUNTER).parent('div').parent('div').remove();
});
});
Please update script or check this fiddle http://jsfiddle.net/Cne2Q/
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#TextBoxesGroup" +COUNTER).remove();
});
What you're doing here, - you're trying to remove an element like $("#TextBoxesGroup1") which obviously doesn't exist. So what you need to do is modify your create new input like this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div id="textBoxContainer'+COUNTER+'" class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
and your remove button
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#textBoxContainer" +COUNTER).remove();
});