I need some help in calculating the sum of the numbers a user has entered, and display it automatically. When the user delete one number the sum should also auto calculate.
$('.col-lg-1').change(function() {
var total = 0;
$('.col-lg-1').each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
$('#result').html(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-1">
<label>TEST 1 </label>
<input type="hidden" name="section_id" value="<?php echo $section_id; ?>">
<input type="hidden" name="session_id" value="<?php echo $session_id; ?>">
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
<input type="hidden" name="class_id" value="<?php echo $class_id; ?>">
<input type="number" name="mt_ca1" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1" id="t2">
<label>TEST 2</label>
<input type="number" name="mt_ca2" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1" id="assg">
<label>TEST 3</label>
<input type="number" name="mt_ca3" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1">
<label>TOTAL</label>
<output id="result"></output>
</div>
Almost there. You are targeting '.col-lg-1' which are divs, not inputs. You need to target the inputs in order to read their values.
const $inputs = $('input[type="number"]')
$inputs.change(function() {
var total = 0;
$inputs.each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
$('#result').html(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-1">
<label>TEST 1 </label>
<input type="hidden" name="section_id" value="<?php echo $section_id; ?>">
<input type="hidden" name="session_id" value="<?php echo $session_id; ?>">
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
<input type="hidden" name="class_id" value="<?php echo $class_id; ?>">
<input type="number" name="mt_ca1" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1" id="t2">
<label>TEST 2</label>
<input type="number" name="mt_ca2" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1" id="assg">
<label>TEST 3</label>
<input type="number" name="mt_ca3" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1">
<label>TOTAL</label>
<output id="result"></output>
</div>
.col-lg-1 is a DIV - you're attaching a change event and trying to get this.value from a DIV which will not work.
Instead, cache your inputs and (on "input" event) .reduce() their values into an integer:
jQuery($ => {
const $inp = $(".input-sm"); //PS: Use a more specific selector than this one
const $res = $("#result");
$inp.on("input", () => {
const total = $inp.get().reduce((acc, el) => (acc += parseInt(el.value, 10) || 0), 0);
$res.text(total);
});
});
<div>
<label>TEST 1 </label>
<input type="number" name="mt_ca1" class="inp form-control input-sm rounded-0" required value="0">
</div>
<div class="col-lg-1" id="t2">
<label>TEST 2</label>
<input type="number" name="mt_ca2" class="form-control input-sm rounded-0" required value="0">
</div>
<div class="col-lg-1" id="assg">
<label>TEST 3</label>
<input type="number" name="mt_ca3" class="form-control input-sm rounded-0" required value="0">
</div>
<div class="col-lg-1">
<label>TOTAL</label>
<output id="result"></output>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
your each element is number type and have same classes 'form-control', 'input-sm', & 'rounded-0'.
so either
$('input[type=number]').change(function() {
var total = 0;
$('input[type=number]').each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
$('#result').html(total);
});
or
$('.rounded-0').change(function() {
var total = 0;
$('.rounded-0').each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
$('#result').html(total);
});
can be used.
Related
I try to create dynamic form that will allow user to select option and populate price automatically in input field but unfortunately it only work in first field, it does not work in another added field. please help.
Here is my code
<select class="form-control item" name="madic" id="medicine" required>
<option value="" selected >Select Madicine</option>
<?php
$query2 ="SELECT * FROM pharmacy WHERE Qty != '0'";
$result2 = $con->query($query2);
if($result2->num_rows> 0){
while($optionData1=$result2->fetch_assoc()){
$mid =$optionData1['p_id'];
$madicine =$optionData1['madicine'];
$mrate =$optionData1['mrate_price'];?>
?>
<option value="<?php echo $mid ?>" data-price=<?php echo $mrate; ?>><?php echo $madicine; ?></option>
<?php }} ?>
</select>
</div>
<div class="col col-md-2">
<input type="text" name="mrate[]" value="0" class="mrate form-control " id="mrate" readonly>
</div>
<div class="col col-md-1">
<input type="text" name="Qty[]" class="form-control Qty" value="1" id="Qty" >
</div>
<div class="col col-md-1">
<input type="text" name="mdiscount[]" class="form-control mdiscount" value="0" id="mdiscount" >
</div>
<div class="col col-md-2">
<input type="text" name="pack[]" class="form-control" placeholder="eg: Tab,box .." >
</div>
<div class="col col-md-1">
<button type="button" id="add" class="btn btn-success">+</button>
</div>
JQUERY
$('select[name="madic"]').change(mediSum);
function mediSum(){
var elemente = $('select[name="madic"]').find('option:selected');
var desc1 = Number(elemente.data("price"));
var rate2 = $('.mrate').val(desc1);
}
Here I have Appended
$(document).ready(function(){
var i = i;
$('#add').click(function(){
i++;
$('#mad').append('<div id="row'+i+'"><div class="col col-md-4"><select class="form-control medicine" name="madic[]" id="medicine" required><option value="" selected >Select Madicine</option><?php
$query2 ="SELECT * FROM pharmacy WHERE Qty != '0'";
$result2 = $con->query($query2);
if($result2->num_rows> 0){
while($optionData1=$result2->fetch_assoc()){
$mid =$optionData1['p_id'];
$madicine =$optionData1['madicine'];
$mrate =$optionData1['mrate_price'];?>
?><option value="<?php echo $mid ?>" data-price=<?php echo $mrate; ?>"><?php echo $madicine; ?></option><?php }} ?>
</select></div><div class="col col-md-2"><input type="text" name="mrate[]" value="0" class="mrate form-control " id="mrate" readonly></div><div class="col col-md-1"><input type="number" name="Qty[]" class="form-control Qty" value="1" id="Qty" ></div><div class="col col-md-1"> <input type="number" name="mdiscount[]" class="form-control discount" value="0" id="mdiscount" ></div><div class="col col-md-2"><input type="text" name="pack[]" class="form-control" placeholder="eg: Tab,box .." ></div><div class="col col-md-1"><button type="button" id="'+i+'" class="btn btn-danger remove_row">-</button></div></div>');
});
$(document).on('click','.remove_row', function(){
var row_id = $(this).attr('id');
$('#row'+row_id+'').remove();
});
});
$(document).ready(function(){
var i = i;
$('#add').click(function(){
i++;
$('#mad').append('<div id="row'+i+'"><div class="col col-md-4"><select class="form-control medicine" name="madic[]" id="medicine" required><option value="" selected >Select Madicine</option><option value="1" data-price="125">Amoxline1</option><option value="2" data-price="163">Amoxline2</option><option value="3" data-price="723">Amoxline3</option>
</select></div><div class="col col-md-2"><input type="text" name="mrate[]" value="0" class="mrate form-control " id="mrate" readonly></div><div class="col col-md-1"><input type="number" name="Qty[]" class="form-control Qty" value="1" id="Qty" ></div><div class="col col-md-1"> <input type="number" name="mdiscount[]" class="form-control discount" value="0" id="mdiscount" ></div><div class="col col-md-2"><input type="text" name="pack[]" class="form-control" placeholder="eg: Tab,box .." ></div><div class="col col-md-1"><button type="button" id="'+i+'" class="btn btn-danger remove_row">-</button></div></div>');
});
$(document).on('click','.remove_row', function(){
var row_id = $(this).attr('id');
$('#row'+row_id+'').remove();
});
});
$('select[name="madic"]').change(mediSum);
function mediSum(){
var elemente = $('select[name="madic"]').find('option:selected');
var desc1 = Number(elemente.data("price"));
var rate2 = $('.mrate').val(desc1);
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--- madicine row ----->
<div class="row col col-md-12 madi" id="mad" style="display: block;">
<br>
<div class="col col-md-4">
<select class="form-control item" name="madic" id="medicine" required>
<option value="" selected >Select Madicine</option>
<option value="1" data-price="125">Amoxline1</option>
<option value="2" data-price="163">Amoxline2</option>
<option value="3" data-price="723">Amoxline3</option>
<?php }} ?>
</select>
</div>
<div class="col col-md-2">
<input type="text" name="mrate[]" value="0" class="mrate form-control " id="mrate" readonly>
</div>
<div class="col col-md-1">
<input type="text" name="Qty[]" class="form-control Qty" value="1" id="Qty" >
</div>
<div class="col col-md-1">
<input type="text" name="mdiscount[]" class="form-control mdiscount" value="0" id="mdiscount" >
</div>
<div class="col col-md-2">
<input type="text" name="pack[]" class="form-control" placeholder="eg: Tab,box .." >
</div>
<div class="col col-md-1">
<button type="button" id="add" class="btn btn-success">+</button>
</div>
</div><!-- end medicines -->
Example of what I want when user select then data-price value display in next input field even when I add another row.
When you called
$('select[name="madic"]').change(mediSum);
you have specified that all select tags existent (at the time) in the document, having the name of madic should handle change events by calling mediSum. However, when such a select is created later, it does not have this handler. So, I recommend changing your code to:
$('select[name="madic"]:not(.initialized)').change(mediSum).addClass('initialized');
So, any select tags having the name of madic that were not initialized (we know that by the fact that they don't have the initialized class yet) will be associated with the given change handler and will receive the initialized class. Now, you have a feature that dynamically adds similar select tags. Those new tags will not have the initialized class, so running the same code when the add event happens as the one suggested above should solve your issue.
There is a section in my school web app that allows me to add scores for all students of a specific class at once.
I recently added some codes that automatically calculates the sum of input values with javascript.
It works fine. Problem is, scores of all students are been added up as one to just one student at the top.
Please see image below
I want each student to have their own total score.
<?php }elseif($class_id >= 15 && $class_id <= 17){ ?>
<form action="<?php echo site_url('admin/mtprimary/assigngradeActionMT') ?>" method="POST" id="formSubjectTeacher">
<?php echo $this->customlib->getCSRF(); ?>
<div class="row">
<div class="col-lg-3">
<input type="hidden" name="class" value="<?php echo $class_id; ?>">
<input type="hidden" name="subject_id" value="<?php echo $subject_id; ?>">
</div>
<div class="col-lg-4">
<h4><strong><?php echo $session_name; ?></strong></h4>
</div>
</div>
<br>
<hr>
<?php foreach($students as $student){?>
<div class="row">
<div class="col-lg-3">
<div class="form-group">
<label>Student Name</label>
<input type="hidden" name="number[]" value="">
<input type="hidden" name="section_id" value="<?php echo $section_id; ?>">
<input type="hidden" name="session_id[]" value="<?php echo $student->session_id; ?>">
<input type="hidden" name="student_id[]" value="<?php echo $student->student_id; ?>">
<input type="hidden" name="class_id[]" value="<?php echo $class_id; ?>">
<input type="text" value="<?php echo $CI->GetStudentNameWithID($student->student_id); ?>" class="form-control " readonly>
</div>
</div>
<div class="col-lg-1">
<label>Test1 </label>
<input type="hidden" name="session_id[]" value="<?php echo $sessionID; ?>">
input type="number" name="mt_ca1[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="t2">
<label>Test2</label>
<input type="number" name="mt_ca2[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="assg">
<label>Test3</label>
<input type="number" name="mt_ca3[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1">
<label>Total</label>
<output id="result"></output>
</div>
</div>
<script>
const $inputs = $('input[type="number"]')
$inputs.change(function() {
var total = 0;
$inputs.each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
$('#result').html(total);
});
</script>
As has been pointed out, you have multiple elements with an id of result which is not allowed, you should use a class of result instead. But your main problem is that you need to qualify the inputs that you sum to get the total score for a student. You can do this by finding the parent div with class row for the input which changes, and then only sum the inputs that are children of that div. You can then store the total to the result output which is a child of that div:
const $inputs = $('input[type="number"]')
$inputs.change(function() {
var total = 0;
var parent = $(this).closest('.row');
parent.find('input[type="number"]').each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
parent.find('.result').html(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-3">
<div class="form-group">
<label>Student Name</label>
<input type="hidden" name="number[]" value="">
<input type="hidden" name="section_id" value="1">
<input type="hidden" name="session_id[]" value="5">
<input type="hidden" name="student_id[]" value="1">
<input type="hidden" name="class_id[]" value="1">
<input type="text" value="Bill" class="form-control " readonly>
</div>
</div>
<div class="col-lg-1">
<label>Test1 </label>
<input type="hidden" name="session_id[]" value="<?php echo $sessionID; ?>">
<input type="number" name="mt_ca1[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="t2">
<label>Test2</label>
<input type="number" name="mt_ca2[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="assg">
<label>Test3</label>
<input type="number" name="mt_ca3[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1">
<label>Total</label>
<output class="result"></output>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<div class="form-group">
<label>Student Name</label>
<input type="hidden" name="number[]" value="">
<input type="hidden" name="section_id" value="1">
<input type="hidden" name="session_id[]" value="5">
<input type="hidden" name="student_id[]" value="2">
<input type="hidden" name="class_id[]" value="1">
<input type="text" value="Mary" class="form-control " readonly>
</div>
</div>
<div class="col-lg-1">
<label>Test1 </label>
<input type="hidden" name="session_id[]" value="<?php echo $sessionID; ?>">
<input type="number" name="mt_ca1[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="t2">
<label>Test2</label>
<input type="number" name="mt_ca2[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="assg">
<label>Test3</label>
<input type="number" name="mt_ca3[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1">
<label>Total</label>
<output class="result"></output>
</div>
</div>
The attribute id must be unique in a document, use class instead. First change the HTML with class.
From
<output id="result"></output>
To
<output class="result"></output>
In jQuery Change
$('#result').html(total);
To
$(this).parent().next().find('.result').text(total);
Please Note: It is good practice to use text() instead of html() if the the text is plain string (not htmlString).
I will also prefer input event instead of change to output the immediate changes by changing
$inputs.change(function() {
To
$inputs.on('input', function() {
Here is my HTML:
<?php foreach($proddata as $p){ ?>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<input type="checkbox" name="productnames[]" id="productnames" value="<?php echo $p->p_id;?>" style="width:10%;" <?php if(isset($_POST['productnames'])) echo "checked='checked'"; ?> />
<?php echo $p->p_name;?>
</div>
</div>
<div class="col-md-9">
<div class="form-group" id="products">
<input type="number" id="<?php echo "h".$p->p_id;?>" name="<?php echo $p->p_id;?>" class="val" onkeyup="myFunction()" onclick="myFunction()"
value="<?php if(isset($_POST['productnames'])) {echo "1";} ?>" min=1 step=1 placeholder="height"/>
<input type="number" id="<?php echo "w".$p->p_id;?>" name="<?php echo $p->p_id;?>" class="val" onkeyup="myFunction()" onclick="myFunction()"
value="<?php if(isset($_POST['productnames'])) {echo "1";} ?>" min=1 step=1 placeholder="width"/>
<input type="number" id="<?php echo "qt".$p->p_id;?>" name="<?php echo $p->p_id;?>" class="val" onkeyup="myFunction()" onclick="myFunction()" value="<?php if(isset($_POST['productnames'])) {echo "1";} ?>" min=1 step=1 placeholder="quantity"/>
<input type="text" id="<?php echo "r".$p->p_id;?>" value="" placeholder="Total"/>
<input type="hidden" id="<?php echo $p->p_id;?>" value=""/>
</div>
</div>
</div>
<?php } ?>
JS:
<script>
function myFunction()
{
len = document.getElementById("length_array").value;
for(var i =1;i<=len; i++)
{
h = parseInt(document.getElementById('h'+i.value);
w = parseInt(document.getElementById("w1").value);
q = parseInt(document.getElementById("qt1").value);
if(!h=="" && !w=="" && !q=="")
{
total= h * w * q;
document.getElementById("r1").value = total;
}
}
}</script>
View:
This allows me to calculate total of only 1st row. I need to allow call myfunction() for each product whenever the height and width values are fed into the input boxes. I am stuck. Thnks for the help in advance. :)
Please see the following.
I added some classes and set up the event handler onload
NOTE: IDs must be unique
Also you can create a grand total and add to it in the inner loop too
window.onload = function() {
var vals = document.querySelectorAll(".val");
for (var i = 0; i < vals.length; i++) { // loop over all input with class val
vals[i].oninput = function() {
var tots = document.querySelectorAll(".total");
for (var i = 1; i < tots.length + 1; i++) { // loop over all totals to get index
var h = parseInt(document.getElementById("h" + i).value),
w = parseInt(document.getElementById("w" + i).value),
qt = parseInt(document.getElementById("qt" + i).value);
h = isNaN(h) ? 0 : h;
w = isNaN(w) ? 0 : w;
qt = isNaN(qt) ? 0 : qt;
var total = h * w * qt;
document.getElementById("r" + i).value = total>0?total:"";
}
}
}
vals[0].oninput(); // perform initial calculation
}
<div class="row">
<div class="col-md-3">
<div class="form-group">
<input type="checkbox" name="productnames[]" id="productnames1" value="x" style="width:10%;" /> Name 1
</div>
</div>
<div class="col-md-9">
<div class="form-group" id="products">
<input type="number" id="h1" name="h1" class="val" value="1" min=1 step=1 placeholder="height" />
<input type="number" id="w1" name="w1" class="val" value="1" min=1 step=1 placeholder="width" />
<input type="number" id="qt1" name="qt1" class="val" value="3" min=1 step=1 placeholder="quantity" />
<input type="text" class="total" id="r1" value="" placeholder="Total" />
<input type="hidden" id="x1" value="" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<input type="checkbox" name="productnames[]" id="productnames2" value="x" style="width:10%;" /> Name 2
</div>
</div>
<div class="col-md-9">
<div class="form-group" id="products">
<input type="number" id="h2" name="h2" class="val" value="1" min=1 step=1 placeholder="height" />
<input type="number" id="w2" name="w2" class="val" value="1" min=1 step=1 placeholder="width" />
<input type="number" id="qt2" name="qt2" class="val" value="0" min=0 step=1 placeholder="quantity" />
<input type="text" class="total" id="r2" value="" placeholder="Total" />
<input type="hidden" id="x2" value="" />
</div>
</div>
</div>
I made some change in your code Its working...
Please check
I change the function calling event to onChange() from onkeyup() this call function while making change in inputs.
While calling function send current $p->p_id to function.By this the selection of row get easier.
<?php foreach($proddata as $p){ ?>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<input type="checkbox" name="productnames[]" id="productnames" value="<?php echo $p->p_id;?>" style="width:10%;" <?php if(isset($_POST['productnames'])) echo "checked='checked'"; ?> /><?php echo $p->p_name;?>
</div>
</div>
<div class="col-md-9">
<div class="form-group" id="products">
<input type="number" id="h-<?php echo $p->p_id;?>" name="<?php echo $p->p_id;?>" class="val" onkeyup="myFunction(<?php echo $p->p_id;?>)" value="<?php if(isset($_POST['productnames'])) {echo "1";} ?>" min=1 step=1 placeholder="height" />
<input type="number" id="w-<?php echo $p->p_id;?>" name="<?php echo $p->p_id;?>" class="val" onkeyup="myFunction(<?php echo $p->p_id;?>)" value="<?php if(isset($_POST['productnames'])) {echo "1";} ?>" min=1 step=1 placeholder="width" />
<input type="number" id="q-<?php echo $p->p_id;?>" name="<?php echo $p->p_id;?>" class="val" onkeyup="myFunction(<?php echo $p->p_id;?>)" value="<?php if(isset($_POST['productnames'])) {echo "1";} ?>" min=1 step=1 placeholder="quantity" />
<input type="text" id="<?php echo "r".$p->p_id;?>" value="" placeholder="Total"/>
<input type="hidden" id="<?php echo $p->p_id;?>" value=""/>
</div>
</div>
</div>
<?php } ?>
<script>
function myFunction(id){
h = parseInt(document.getElementById('h-'+id).value);
w = parseInt(document.getElementById('w-'+id).value);
q = parseInt(document.getElementById('q-'+id).value);
if(!h)h=1;
if(!w)w=1;
if(!q)q=1;
total= h * w * q;
document.getElementById('r-'+id).value = total;
}
</script>
Actually I want to add text fields by clicking on button. It is working but I am unable to remove the text fields by clicking on remove button. Please see the code below:
<script type="text/javascript">
var i = 1;
function more_fields() {
i++;
var objTo = document.getElementById('more_fields')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass"+i);
var rdiv = 'removeclass'+i;
divtest.innerHTML = '<div><input type="text" name="comp[]" id="component"
value="" placeholder="Product" /> <input type="number"
name="quantity[]" id="quantity" placeholder="Quantity" /> <input
type="number" name="rate[]" id="rate" placeholder="Rate" /> <input
type="number" name="amount[]" id="amount" placeholder="Amount" readonly />
<button class="btn btn-danger" type="button" onclick="remove_more_fields('+
i +');" style="height:2em; width:3%;">X</button></div>';
objTo.appendChild(divtest)
}
function remove_more_fields(rid) {
$('.removeclass'+rid).remove();
}
</script>
<div class="form-group fieldgroup" id="more_fields">
<div>
<input type="text" name="comp[]" id="component" value=""
placeholder="Product" />
<input type="number" name="quantity[]"
id="quantity" placeholder="Quantity"/>
<input type="number" name="rate[]"
id="rate" placeholder="Rate" />
<input type="number" name="amount[]"
id="amount" placeholder="Amount" readonly/>
<button class="add_field_button"
type="button" onclick="more_fields()"> Add</button>
</div>
<br/>
</div>
How can I get that result? And I want to calculate the quantity*rate and display the result automatically in Amount field. If I change either quantity or rate, automatically amount will change and display the result. Please suggest me...Thank you.
Try this to get amount:
<div class="form-group fieldgroup" id="more_fields">
<div>
<input type="text" name="comp[]" id="component" value="" placeholder="Product" />
<input type="number" name="quantity[]" id="quantity" placeholder="Quantity" onchange="getAmount(this)" />
<input type="number" name="rate[]" id="rate" placeholder="Rate" onchange="getAmount(this)" />
<input type="number" name="amount[]" id="amount" placeholder="Amount" readonly/>
<button class="add_field_button" type="button" onclick="more_fields()"> Add</button>
</div>
<br/>
</div>
<script>
var i = 1;
function more_fields() {
i++;
var objTo = document.getElementById('more_fields');
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass" + i);
var rdiv = 'removeclass' + i;
divtest.innerHTML = '<div><input type="text" name="comp[]" id="component" value="" placeholder="Product" /> <input type="number" name="quantity[]" id="quantity" placeholder="Quantity" onchange="getAmount(this)" /> <input type="number" name="rate[]" id="rate" placeholder="Rate" onchange="getAmount(this)" /> <input type="number" name="amount[]" id="amount" placeholder="Amount" readonly /> <button class="btn btn-danger" type="button" onclick="remove_more_fields(' + i + ');" style="height:2em; width:3%;">X</button></div>';
objTo.appendChild(divtest)
}
function remove_more_fields(rid) {
$('.removeclass' + rid).remove();
}
function getAmount(el)
{
console.log(el.parentElement);
var inputs = el.parentElement.getElementsByTagName('input');
inputs[3].value = (parseInt(inputs[1].value) * parseFloat(inputs[2].value));
}
</script>
Here is working JSFiddle
Give the onclick function fro remove button like this - onclick="remove_more_fields(i);" . This would make the function call with value of i being passed to remove_more_fields function.
What I missed telling here is you can include the entire divtest.innerHTML definition in - <div>...</div> (note the quote here) , since my editor was showing error for the string spanning multiple lines. This might have triggered the evaluation of i and it worked perfectly fine for me.
I'm stuck on part of my project where user should just keep filling the form and new lines should be added automatically when user focused on last input in the form. I'm not forged in JS/jQ so maybe one of you could help me... It is working but still just from the 1st line, not from the duplicated ones. Thanks is advance
<form class="form-inline" method="post" action="loadin.php">
<!-- form header -->
<hr>
<div class="form-group">
<select class="form-control" name="vendor" id="vendor">
<?php
foreach($vendors_ as $v){
echo"<option value='".$v['ID']."'>".ucfirst($v['name'])."</option>";
}
?>
</select>
<input type="text" class="form-control" name="invoice" id="invoice" placeholder="Faktrura">
<input type="text" class="form-control" name="date" id="date" placeholder="Datum" value="<?php echo date("Y-m-d") ?>">
<button type="submit" name="LoadItems" class="btn btn-default"><i class="fa fa-check" aria-hidden="true"></i> Nahrát</button>
</div>
<hr>
<!-- form lines -->
<div class="duplicate" style="margin-bottom: 5px;">
<div class="form-group">
<input type="hidden" class="form-control cleanVal" name="row[]" id="row">
<select class="form-control" name="category[]" id="category">
<?php
foreach($types_ as $t){
echo"<option value='".$t['ID']."'>".ucfirst($t['name'])."</option>";
}
?>
</select>
<input type="text" class="form-control cleanVal" name="item[]" id="item" placeholder="Položka">
<input type="text" class="form-control cleanVal" name="package[]" id="package" placeholder="Balení">
<input type="text" class="form-control cleanVal" name="amount[]" id="amount" placeholder="Množství">
<input type="text" class="form-control cleanVal" name="price[]" id="price" placeholder="Cena">
<input type="text" class="form-control cleanVal" name="atest[]" id="atest" placeholder="Atest">
<input type="text" class="form-control cleanVal" name="batch[]" id="batch" placeholder="Sarže">
<input type="text" class="form-control cleanVal" name="expire[]" id="expire" placeholder="Expirace" style="width:80px">
<input type="text" class="form-control cleanVal x" name="vat[]" id="vat" placeholder="DPH" style="width:45px">
</div>
</div>
</form>
$(".duplicate:last input").focus(function() {
count++;
var $clone = $('.duplicate:last').clone();
$clone.find("input,select").each(function(){
$(this).attr({
id: $(this).attr("id") + count,
});
});
$("form").append($clone);
$(".duplicate:last .cleanVal").val('');
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
As last element is being changed every time new elements are appended, listen the event on the parent body or any other fixed parent.
var count = 0;
$('body').on('focus', ".duplicate:last input", function() {
count++;
var $clone = $('.duplicate:last').clone();
$clone.find("input,select").each(function() {
$(this).attr({
id: $(this).attr("id") + count,
});
});
$("form").append($clone);
$(".duplicate:last .cleanVal").val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form class="form-inline" method="post" action="loadin.php">
<hr>
<div class="form-group">
<select class="form-control" name="vendor" id="vendor">
</select>
<input type="text" class="form-control" name="invoice" id="invoice" placeholder="Faktrura">
<input type="text" class="form-control" name="date" id="date" placeholder="Datum" value="">
<button type="submit" name="LoadItems" class="btn btn-default"><i class="fa fa-check" aria-hidden="true"></i> Nahrát</button>
</div>
<hr>
<div class="duplicate" style="margin-bottom: 5px;">
<div class="form-group">
<input type="hidden" class="form-control cleanVal" name="row[]" id="row">
<select class="form-control" name="category[]" id="category">
</select>
<input type="text" class="form-control cleanVal" name="item[]" id="item" placeholder="Položka">
<input type="text" class="form-control cleanVal" name="package[]" id="package" placeholder="Balení">
<input type="text" class="form-control cleanVal" name="amount[]" id="amount" placeholder="Množství">
<input type="text" class="form-control cleanVal" name="price[]" id="price" placeholder="Cena">
<input type="text" class="form-control cleanVal" name="atest[]" id="atest" placeholder="Atest">
<input type="text" class="form-control cleanVal" name="batch[]" id="batch" placeholder="Sarže">
<input type="text" class="form-control cleanVal" name="expire[]" id="expire" placeholder="Expirace" style="width:80px">
<input type="text" class="form-control cleanVal x" name="vat[]" id="vat" placeholder="DPH" style="width:45px">
</div>
</div>
</form>
Fiddle Demo
You must define your focus event as bellow:
$('body').on('focus', ".duplicate:last input", function() {
// codes here
}