I have a dynamic form for items. First row items form will appear with (+) and (-) button, next they click (+) button and (-) in the previous row and now I have problem when I want to remove row that has (+) and (-), I need to add (+) button on previous row. I read about closest and find, but I cant use it.
here is my html
var index = 1;
$(document).ready(function() {
addItems(index);
});
function addItems(index) {
$('#btn-add-item').remove();
$('#item_list').append(
"<div class='items' id='item_" + index + "'>" +
"<div class='row'>" +
"<div class='col-md-3'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_qty[]' placeholder='Item qty' data-error='Item qty cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-7'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_name[]' placeholder='Item name' data-error='Item name cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-2' id='btn_action'>" +
"<button id='btn-remove-item' type='button' class='btn btn-danger' style='margin-right: 5px' onclick='removeItem(" + index + ")'><i class='fa fa-minus'></i></button>" +
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>" +
"</div>" +
"</div>" +
"</div>"
);
index++;
}
function removeItem(index) {
$('#item_' + index).closest("items").find("#btn_action").append(
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>"
);
$('#item_' + index).remove();
index--;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="row bg-title">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
<h4 class="page-title">Tambah Transaksi</h4>
</div>
<div class="col-lg-9 col-sm-8 col-md-8 col-xs-12">
<ol class="breadcrumb">
<li>Transaksi</li>
<li class="active">Tambah Transaksi</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="white-box">
<form action="#" class="form">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nomor Transaksi</label>
<input type="text" class="form-control" name="transaction_number" id="transaction_number" disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nama Pembeli</label>
<input type="text" class="form-control" name="buyer_name" id="buyer_name">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Alamat Pembeli</label>
<textarea type="text" class="form-control" name="buyer_address" id="buyer_address" cols="10" rows="5"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Items</label>
</div>
</div>
</div>
<div id="item_list"></div>
</form>
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="white-box">
</div>
</div>
</div>
Thanks for your help guys.
What you are looking for is .prev and not .closest.
As correctly pointed out by #Priyal Pithadiya, you will need to add a check before you add element.
var $item = $('#item_' + index)
var shouldAppendButton = !!$item.find('#btn-add-item').length;
if (shouldAppendButton)
$item
.prev()
.find("#btn_action")
.append(
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>"
);
$item.remove();
Explanation
.closest: It looks in the hierarchy and get to the necessary element. It does not look for previous sibling.
.prev: It looks for previous sibling.
Sample:
var index = 1;
$(document).ready(function() {
addItems(index);
});
function addItems(index) {
$('#btn-add-item').remove();
$('#item_list').append(
"<div class='items' id='item_" + index + "'>" +
"<div class='row'>" +
"<div class='col-md-3'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_qty[]' placeholder='Item qty' data-error='Item qty cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-7'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_name[]' placeholder='Item name' data-error='Item name cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-2' id='btn_action'>" +
"<button id='btn-remove-item' type='button' class='btn btn-danger' style='margin-right: 5px' onclick='removeItem(" + index + ")'><i class='fa fa-minus'></i></button>" +
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>" +
"</div>" +
"</div>" +
"</div>"
);
index++;
}
function removeItem(index) {
var $item = $('#item_' + index)
var shouldAppendButton = !!$item.find('#btn-add-item').length;
if(shouldAppendButton)
$item
.prev()
.find("#btn_action")
.append(
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>"
);
$item.remove();
index--;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="row bg-title">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
<h4 class="page-title">Tambah Transaksi</h4>
</div>
<div class="col-lg-9 col-sm-8 col-md-8 col-xs-12">
<ol class="breadcrumb">
<li>Transaksi</li>
<li class="active">Tambah Transaksi</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="white-box">
<form action="#" class="form">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nomor Transaksi</label>
<input type="text" class="form-control" name="transaction_number" id="transaction_number" disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nama Pembeli</label>
<input type="text" class="form-control" name="buyer_name" id="buyer_name">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Alamat Pembeli</label>
<textarea type="text" class="form-control" name="buyer_address" id="buyer_address" cols="10" rows="5"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Items</label>
</div>
</div>
</div>
<div id="item_list"></div>
</form>
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="white-box">
</div>
</div>
</div>
Pointers:
IDs must be unique. Having same id in all items div is wrong.
You can also add a delegate instead of adding handlers in every item's markup
Related
I'm developing a Will generating web application. For this I need to develop a system which allow the user to add multiple beneficiaries.
I have written some code which is working for creation on new beneficiary but the issue is when a user deletes a beneficiary the sequence number doesn't work accordingly.
For example, User added 5 beneficiaries and he deletes the 3rd beneficiary the sequence number doesn't change. i.e. beneficiary 1, beneficiary 2, beneficiary 4, beneficiary 5. I want to sort this problem make them in sequence.
For my code please check this
https://jsfiddle.net/shahzadwaris/purvo4bn/5/
$(document).delegate(".delBeneficiary", "click", function(e) {
e.preventDefault();
var div = $(this).attr("id");
var nmbr = div.replace(/\D/g, "");
$("." + div).remove();
bene--;
//alert(nmbr);
});
var bene = 2;
$(".addBeneficiary").click(function(e) {
e.preventDefault();
addBeneficiary(bene);
bene++;
});
$(document).delegate(".addBeneficiaryD", "click", function(e) {
e.preventDefault();
addBeneficiary(bene);
bene++;
});
function addBeneficiary(bene) {
$("#beneficiaries").append(
"<div class = 'bene" +
bene +
"'><h6 class = 'mt-3 mb-3'><b>Beneficiary <span class = 'bNmbr'>" +
bene +
"</span></b></h6>" +
"<div class='form-group row'>" +
"<label for='ename' class='col-sm-4 col-form-label backgroundForm pt-2 pb-2'><span class = 'pt-5'>Name</span><span class = 'text-danger'> *</span></label>" +
"<div class='col-sm-7'>" +
" <input type='text' class='form-control p-1 mt-1' id='ename' name = 'ebname[]' placeholder='Name'>" +
"</div>" +
"<label for='enric' class='col-sm-4 col-form-label backgroundForm pt-2 pb-2'><span class = 'pt-5'>NRIC / Passport No.</span><span class = 'text-danger'> *</span></label>" +
"<div class='col-sm-7'>" +
"<input type='text' class='form-control p-1 mt-1' id='enric' name = 'ebnric[]' placeholder='NRIC / Passport No'>" +
"</div> " +
"<label for='relationship' class='col-sm-4 col-form-label backgroundForm pt-2 pb-2'><span class = 'pt-5'>Relationship</span></label>" +
"<div class='col-sm-7'>" +
"<input type='text' class='form-control p-1 mt-1' id='Rrelationship' name = 'ebrelationship[]' placeholder='Relationship'>" +
"</div>" +
"<div class = 'col-xs-12 col-sm-12 col-md-11 mt-2 text-right'>" +
"<button class = 'btn btn-sm addBeneficiaryD ' id = 'bene" +
bene +
"' >Add</button>" +
"<button class = 'btn btn-sm delBeneficiary ml-2' id = 'bene" +
bene +
"'>Delete</button>" +
"</div>" +
"</div></div>"
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h6 class='mt-3 mb-3'><b>Beneficiary <span class = 'bNmbr'>1</span></b></h6>
<div class="form-group row">
<label for="ename" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2"><span class = 'pt-5'>Name</span><span class = 'text-danger'> *</span></label>
<div class="col-sm-7">
<input type="text" class="form-control p-1 mt-1" id="ename" name='ebname[]' placeholder="Name" required='required' />
</div>
<label for="enric" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2"><span class = 'pt-5'>NRIC / Passport No.</span><span class = 'text-danger'> *</span></label>
<div class="col-sm-7">
<input type="text" class="form-control p-1 mt-1" id="enric" name='ebnric[]' placeholder="NRIC / Passport No" required='required' />
</div>
<label for="relationship" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2"><span class = 'pt-5'>Relationship</span></label>
<div class="col-sm-7">
<input type="text" class="form-control p-1 mt-1" id="Rrelationship" name='ebrelationship[]' placeholder="Relationship" required='required' />
</div>
<div class='col-xs-12 col-sm-10 col-md-8 mt-2 text-right'>
<button class='btn btn-sm addBeneficiary '>Add</button>
</div>
</div>
<div id='beneficiaries'>
</div>
You can start here
Much simpler code and removed the deprecated delegate
function renum() {
$(".beneficiary").each(function() {
$(this).find(".bNmbr").text($(this).index()+1)
})
}
$(".delBeneficiary").eq(0).hide()
$(document).on("click", ".delBeneficiary ", function(e) {
e.preventDefault();
$(this).closest(".beneficiary").remove();
renum();
});
$(document).on("click", ".addBeneficiary", function(e) {
e.preventDefault();
const beneCount = $(".beneficiary").length;
let $bene = $(this).closest(".beneficiary").clone();
$bene.find("input").each(function() { $(this).val("") }); // empty inputs
$bene.find("[id]").each(function() {
this.id += beneCount;
})
$bene.find(".bNmbr").text(beneCount + 1)
$bene.appendTo("#beneficiaries")
$(".delBeneficiary:gt(0)").show();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='beneficiaries'>
<div class="beneficiary">
<h6 class='mt-3 mb-3'><b>Beneficiary <span class = 'bNmbr'>1</span></b></h6>
<div class="form-group row">
<label for="ename" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2"><span class = 'pt-5'>Name</span><span class = 'text-danger'> *</span></label>
<div class="col-sm-7">
<input type="text" class="form-control p-1 mt-1" id="ename" name='ebname[]' placeholder="Name" required='required' />
</div>
<label for="enric" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2"><span class = 'pt-5'>NRIC / Passport No.</span><span class = 'text-danger'> *</span></label>
<div class="col-sm-7">
<input type="text" class="form-control p-1 mt-1" id="enric" name='ebnric[]' placeholder="NRIC / Passport No" required='required' />
</div>
<label for="relationship" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2"><span class = 'pt-5'>Relationship</span></label>
<div class="col-sm-7">
<input type="text" class="form-control p-1 mt-1" id="Relationship" name='ebrelationship[]' placeholder="Relationship" required='required' />
</div>
<div class='col-xs-12 col-sm-10 col-md-8 mt-2 text-right'>
<button class='btn btn-sm addBeneficiary '>Add</button>
<button class='btn btn-sm delBeneficiary ml-2'>Delete</button>
</div>
</div>
</div>
</div>
Try renumbering your entries every time you add or delete:
function renumber() {
var i = 1;
$('.bNmbr').each(function(){
this.innerHTML = i;
++i;
});
}
Can be combined with the code by mplungjan.
This would be a complete code for you. I tried to make it easier for editing and removed duplicate ID creations:
var bene = 1;
function correctNumbers() {
$('.bNmbr').each(function(i) {
$(this).text(i + 1);
});
};
$('body').on('click', '.addBeneficiary', function(e) {
e.preventDefault();
bene++;
addBeneficiary(bene);
});
$('body').on('click', '.delBeneficiary', function(e) {
e.preventDefault();
$(this).closest('.bene').remove();
correctNumbers();
});
function addBeneficiary(bene) {
$("#beneficiaries").append('\
<div class="bene" id="bene' + bene + '">\
<h6 class="mt-3 mb-3"><b>Beneficiary <span class="bNmbr">' + bene + '</span></b></h6>\
<div class="form-group row">\
<label for="ename' + bene + '" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2">\
<span class="pt-5">Name</span>\
<span class="text-danger"> *</span>\
</label>\
<div class="col-sm-7">\
<input type="text" class="form-control p-1 mt-1" id="ename' + bene + '" name="ebname[]" placeholder="Name">\
</div>\
<label for="enric' + bene + '" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2">\
<span class="pt-5">NRIC / Passport No.</span>\
<span class="text-danger"> *</span>\
</label>\
<div class="col-sm-7">\
<input type="text" class="form-control p-1 mt-1" id="enric' + bene + '" name="ebnric[]" placeholder="NRIC / Passport No">\
</div>\
<label for="relationship' + bene + '" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2">\
<span class="pt-5">Relationship</span>\
</label>\
<div class="col-sm-7">\
<input type="text" class="form-control p-1 mt-1" id="relationship' + bene + '" name="ebrelationship[]" placeholder="Relationship">\
</div>\
<div class="col-xs-12 col-sm-12 col-md-11 mt-2 text-right">\
<button class="btn btn-sm addBeneficiary" id="add' + bene + '">Add</button>\
<button class="btn btn-sm delBeneficiary ml-2" id="delete' + bene + '">Delete</button>\
</div>\
</div>\
</div>\
');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h6 class='mt-3 mb-3'><b>Beneficiary <span class='bNmbr'>1</span></b></h6>
<div class="form-group row">
<label for="ename" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2"><span class='pt-5'>Name</span><span class='text-danger'> *</span></label>
<div class="col-sm-7">
<input type="text" class="form-control p-1 mt-1" id="ename" name='ebname[]' placeholder="Name" required='required' />
</div>
<label for="enric" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2"><span class='pt-5'>NRIC / Passport No.</span><span class='text-danger'> *</span></label>
<div class="col-sm-7">
<input type="text" class="form-control p-1 mt-1" id="enric" name='ebnric[]' placeholder="NRIC / Passport No" required='required' />
</div>
<label for="relationship" class="col-sm-4 col-form-label backgroundForm pt-2 pb-2"><span class='pt-5'>Relationship</span></label>
<div class="col-sm-7">
<input type="text" class="form-control p-1 mt-1" id="Rrelationship" name='ebrelationship[]' placeholder="Relationship" required='required' />
</div>
<div class='col-xs-12 col-sm-12 col-md-11 mt-2 text-right'>
<button class='btn btn-sm addBeneficiary '>Add</button>
</div>
</div>
<div id='beneficiaries'>
</div>
Also on JSFiddle
var str ="";
var counter=0;
$(document).ready(function() {
$(".amount, .penalty").change(function() {
var total = 0;
var amount = parseInt($(".amount").val()) || 0;
console.log("amount: "+amount);
var penalty = parseInt($(".penalty").val()) || 0;
console.log("penalty: "+penalty);
total = amount + penalty;
console.log(total);
$("#total").html(total);
});
$(".add").click(function() {
alert();
str +="<div class='form-group row' >"
+"<label class='col-xs-3 col-form-label mr-2'>Reason</label>"
+"<div class='col-xs-9'>"
+ "<input type='text' class='form-control' id='reason"+counter+"' name='reason'>"
+"</div>"
+"<label class='col-xs-3 col-form-label mr-2'>Amount</label>"
+"<div class='col-xs-9'>"
+ "<input type='text' class='form-control amount' id='amount"+counter+"' name='amount'>"
+"</div>"
+ "<label class='col-xs-3 col-form-label mr-2'>Penalty</label>"
+"<div class='col-xs-9'>"
+"<input type='text' class='form-control penalty' id='penalty"+counter+"' name='penalty'>"
+"</div>"
+ "<div class='col-xs-9'>"
+ "<button type='button' class='add'>+</button>"
+ "<button type='button' class='remove'>-</button>"
+ "</div>"
+ "</div>";
counter++;
$("#customsAdd").append(str);
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<!-- <select class="form-control col-md-6">
<option value="1">Customs</option>
<option value="2">VAT</option>
<option value="3">Excise</option>
<option value="4">Others</option>
</select>-->
<!--div for customs!-->
<div class="form-group row" id="forCustoms">
<label class="col-xs-3 col-form-label mr-2">Reason</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="reason" name="reason">
</div>
<label class="col-xs-3 col-form-label mr-2">Amount</label>
<div class="col-xs-9">
<input type="text" class="form-control amount" id="amount" name="amount">
</div>
<label class="col-xs-3 col-form-label mr-2">Penalty</label>
<div class="col-xs-9">
<input type="text" class="form-control penalty" id="penalty" name="penalty">
</div>
<div class="col-xs-9">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<!--div for customs! ends-->
<div id="customsAdd"></div>
<div class="col-md-12">
Total :
<p id="total"></p>
</div>
</div>
</body>
</html>
The total "4" is coming only of first row and upto that my program is correct but when I add the new row then the total is not changing and new row is not added on after clicking "+" button.How to bring new row on "+" button press and change in total?The total is not changing after entering data in 2nd row and "+" is not working.
You have to use .on() for the event to work on dynamically created element. This will allow the event to work on the elements those are added to the body at a later time.
Change:
$(".add").click(function() {
To
$(".container").on("click", ".add", function() {
You can use .map() and reduce() to calculate the total. Try the following way:
var str = "";
var counter = 0;
var total = 0;
$(document).ready(function() {
$(".container").on("input", ".amount, .penalty", function() {
var tArr = $(".amount, .penalty").map(function(i,el){
return Number($(this).val());
}).get();
total = tArr.reduce((a,c) => a+c,0);
//console.log(total);
$("#total").html(total);
});
$(".container").on("click", ".add", function() {
str ="<div class='form-group row' >"
+"<label class='col-xs-3 col-form-label mr-2'>Reason</label>"
+"<div class='col-xs-9'>"
+ "<input type='text' class='form-control' id='reason"+counter+"' name='reason'>"
+"</div>"
+"<label class='col-xs-3 col-form-label mr-2'>Amount</label>"
+"<div class='col-xs-9'>"
+ "<input type='text' class='form-control amount' id='amount"+counter+"' name='amount'>"
+"</div>"
+ "<label class='col-xs-3 col-form-label mr-2'>Penalty</label>"
+"<div class='col-xs-9'>"
+"<input type='text' class='form-control penalty' id='penalty"+counter+"' name='penalty'>"
+"</div>"
+ "<div class='col-xs-9'>"
+ "<button type='button' class='add'>+</button>"
+ "<button type='button' class='remove'>-</button>"
+ "</div>"
+ "</div>";
counter++;
$("#customsAdd").append(str);
});
$(".container").on("click", ".remove", function() {
if($(".form-group.row").length > 1){ // remove only if there is more than one element
$(this).closest('.form-group.row').remove();
$(".amount, .penalty").trigger("input");
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">
<!-- <select class="form-control col-md-6">
<option value="1">Customs</option>
<option value="2">VAT</option>
<option value="3">Excise</option>
<option value="4">Others</option>
</select>-->
<!--div for customs!-->
<div class="form-group row" id="forCustoms">
<label class="col-xs-3 col-form-label mr-2">Reason</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="reason" name="reason">
</div>
<label class="col-xs-3 col-form-label mr-2">Amount</label>
<div class="col-xs-9">
<input type="text" class="form-control amount" id="amount" name="amount">
</div>
<label class="col-xs-3 col-form-label mr-2">Penalty</label>
<div class="col-xs-9">
<input type="text" class="form-control penalty" id="penalty" name="penalty">
</div>
<div class="col-xs-9">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<!--div for customs! ends-->
<div id="customsAdd"></div>
<div class="col-md-12">
Total :
<p id="total"></p>
</div>
</div>
Mamun is right, you need on.
We can make some other improvements too.
We can use your existing row as a template, so if you change your html, you may not need to change your javascript.
You also have a logic issue with your addition function, it won't currently get all fields.
var str ="";
var counter=0;
$(document).ready(function() {
//Use existing row as a template
var rowTemplate = $("#forCustoms").clone(true);
$(".container").on("change", ".amount, .penalty",function() {
var total = 0;
/*NOTE: Not sure what you want to actuall do here
This will always get the fist values, not values
for all
var amount = parseInt($(".amount").val()) || 0;
console.log("amount: "+amount);
var penalty = parseInt($(".penalty").val()) || 0;
console.log("penalty: "+penalty);
*/
/*To Total all values*/
var amount = 0;
var penalty = 0;
$(".form-group,.row").each(function(){
amount += parseInt($(this).find(".amount").val(),10) || 0;
penalty += parseInt($(this).find(".penalty").val(),10) || 0;
})
total = amount + penalty;
console.log(total);
$("#total").html(total);
});
$(".container").on("click" ,".add",function() {
alert();
//Clone our template
var t2 = rowTemplate.clone(true);
//Make Ids Unique
$(t2).attr("id", "row" + counter);
$(t2).find("[name=reason]").attr("id", "reason" + counter);
$(t2).find("[name=amount]").attr("id", "amount" + counter);
$(t2).find("[name=penalty]").attr("id", "penalty" + counter);
counter++;
$("#customsAdd").append(t2);
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<!-- <select class="form-control col-md-6">
<option value="1">Customs</option>
<option value="2">VAT</option>
<option value="3">Excise</option>
<option value="4">Others</option>
</select>-->
<!--div for customs!-->
<div class="form-group row" id="forCustoms">
<label class="col-xs-3 col-form-label mr-2">Reason</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="reason" name="reason">
</div>
<label class="col-xs-3 col-form-label mr-2">Amount</label>
<div class="col-xs-9">
<input type="text" class="form-control amount" id="amount" name="amount">
</div>
<label class="col-xs-3 col-form-label mr-2">Penalty</label>
<div class="col-xs-9">
<input type="text" class="form-control penalty" id="penalty" name="penalty">
</div>
<div class="col-xs-9">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<!--div for customs! ends-->
<div id="customsAdd"></div>
<div class="col-md-12">
Total :
<p id="total"></p>
</div>
</div>
</body>
</html>
I am working on a project in that there is a requirement of dynamically generate html elements, one is date-picker and another one is time range, and it should generate dynamically whenever i click on add row for date-picker and for multiple time ranges.
Can anyone help me how to do this?
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-timepicker/0.5.2/css/bootstrap-timepicker.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-timepicker/0.5.2/js/bootstrap-timepicker.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-12"> </div>
<div class="col-md-12"> </div>
<div id="date-selection">
<div class="row" id="date_count_0">
<div class="col-md-12"> </div>
<div class="col-md-11">
<input type="text" name="date[0]" value="" class="form-control datepicker"/>
</div>
<div class="col-md-1" style="text-align: right;">
<i class="fa fa-plus"></i>
</div>
<div class="col-md-12"> </div>
<div class="col-md-12"> </div>
<div class="timing-selection_0">
<div class="col-md-12">
<div class="row">
<div class="col-md-5">
<input type="text" name="dat[0][from]" value="" class="form-control time-picker" />
</div>
<div class="col-md-5">
<input type="text" name="dat[0][to]" value="" class="form-control time-picker" />
</div>
<div class="col-md-2" style="text-align: right;">
<a href="javascript:void(0);" class="btn btn-info add_timings" id="add_timings_0" data-id="0" onclick="add_timings(this)">
<i class="fa fa-plus"></i>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var date_count = 1;
var time_count = 1;
function add_timings(attr){
var thisid = $(attr).data("id");
var inner_timings = "<div id='delete_timing_" + time_count + "'><div class='col-md-12'> </div>" +
"<div class='col-md-12'>" +
"<div class='row'>" +
"<div class='col-md-5'>" +
"<input type='text' name='dat[" + thisid + "][from]' value='' class='form-control time-picker' /> " +
"</div>" +
"<div class='col-md-5'>" +
"<input type='text' name='dat[" + thisid + "][to]' value='' class='form-control time-picker' /> " +
"</div>" +
"<div class='col-md-2' style='text-align: right;'>" +
"<a href='javascript:void(0);' class='btn btn-info add_timings' id='add_timings_" + time_count + "' onclick='deletetimings(" + time_count + ")'>" +
"<i class='fa fa-minus'></i>" +
"</a> " +
"</div>" +
"</div>" +
"</div>" +
"</div>";
$(".timing-selection_" + thisid).append(inner_timings);
$('.time-picker').timepicker({
template: false,
showInputs: false,
minuteStep: 5
});
time_count++;
}
$("#add_date").on("click", function (row, index) {
var texttoappend = "<div id='delete_row_" + date_count + "'>" +
"<div class='row'>" +
"<div class='col-md-12'> </div>" +
"<div class='col-md-11'>" +
"<input type='text' name='date[" + date_count + "]' value='' class='form-control datepicker' /> " +
"</div>" +
"<div class='col-md-1' style='text-align: right;'>" +
"<a href='javascript:void(0);' class='btn btn-info' onclick='delete_date(" + date_count + ");'><i class='fa fa-minus'></i></a>" +
"</div>" +
"<div class='col-md-12'> </div>" +
"<div class='col-md-12'> </div>" +
"<div class='timing-selection_" + date_count + "'>" +
"<div class='col-md-12'>" +
"<div class='row'>" +
"<div class='col-md-5'>" +
"<input type='text' name='date[" + date_count + "][from]' value='' class='form-control time-picker' /> " +
"</div>" +
"<div class='col-md-5'>" +
"<input type='text' name='date[" + date_count + "][to]' value='' class='form-control time-picker' /> " +
"</div>" +
"<div class='col-md-2' style='text-align: right;'>" +
"<a href='javascript:void(0);' class='btn btn-info add_timings' id='add_timings_"+date_count+"' data-id='"+date_count+"' onclick='add_timings(this)'>"+
"<i class='fa fa-plus'></i>"+
"</a>" +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
"</div>";
"</div>";
$("#date-selection").append(texttoappend + "<br />");
date_count++;
$('.datepicker').datepicker({
format: 'dd/mm/yyyy',
});
$('.time-picker').timepicker({
template: false,
showInputs: false,
minuteStep: 5
});
});
$('.datepicker').datepicker({
format: 'dd/mm/yyyy',
});
$('.time-picker').timepicker({
template: false,
showInputs: false,
minuteStep: 5
});
function delete_date(datecount) {
$("#delete_row_" + datecount).remove();
}
function deletetimings(datecount) {
$("#delete_timing_" + datecount).remove();
}
</script>
</body>
</html>
I had written JavaScript function to add text boxes with on click function. Here i need to show text boxes wherever i want in the page. The textbox code written in p tag with innerHTML but i need to show text boxes in html.
<div class="col-sm-4 col-md-4">
<div class="row">
<label class="control-label col-sm-12 col-md-10"> </label>
<div class="col-sm-4 col-md-4" id="div">
<div id="wrapper">
<div id="field_div">
<span class="glyphicon glyphicon-plus" onclick="add_field();"></span>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-12">Child
</label>
<div class="col-md-12" I need to show text box here instead in javascript </div>
</div>
</div>
</div>
<script>
function add_field() {
var total_text = document.getElementsByClassName("input_text");
total_text = total_text.length + 1;
document.getElementById("field_div").innerHTML = document.getElementById("field_div").innerHTML +
"<p id='input_text" + total_text + "_wrapper'><input type='text' class='input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='text' class='form-control input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='button' value='Remove' onclick=remove_field('input_text" + total_text + "');></p>";
}
function remove_field(id) {
document.getElementById(id + "_wrapper").innerHTML = "";
}
</script>
You are adding the text box in incorrect div. Simply specify the id = 'childDiv' in the lower div and get the text box there.
function add_field() {
var total_text = document.getElementsByClassName("input_text");
total_text = total_text.length + 1;
document.getElementById("childDiv").innerHTML = document.getElementById("childDiv").innerHTML +
"<p id='input_text" + total_text + "_wrapper'><input type='text' class='input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='text' class='form-control input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='button' value='Remove' onclick=remove_field('input_text" + total_text + "');></p>";
}
function remove_field(id) {
document.getElementById(id + "_wrapper").innerHTML = "";
}
<div class="col-sm-4 col-md-4">
<div class="row">
<label class="control-label col-sm-12 col-md-10"> </label>
<div class="col-sm-4 col-md-4" id="div">
<div id="wrapper">
<div id="field_div">
<span class="glyphicon glyphicon-plus" onclick="add_field();">+</span>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-12">Child
</label>
<div id='childDiv' class="col-md-12"> I need to show text box here instead in javascript </div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-12">Child
</label>
<button onclick="add_field()">Add</button>
<div class="col-md-12" id="field_div"> I need to show text box here instead in javascript </div>
</div>
</div>
</div>
<script>
function add_field() {
var total_text = document.getElementsByClassName("input_text");
total_text = total_text.length + 1;
document.getElementById("field_div").innerHTML = document.getElementById("field_div").innerHTML +
"<p id='input_text" + total_text + "_wrapper'><input type='text' class='input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='text' class='form-control input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='button' value='Remove' onclick=remove_field('input_text" + total_text + "');></p>";
}
function remove_field(id) {
document.getElementById(id + "_wrapper").innerHTML = "";
}
</script>
I have a list that has several option. I dynamically set an event that whenever a button is clicked, create a table and text input and put the value of list in in there, but I have option that have number value but it didn't set to the value of that input. See my code.
My jquery code:
$("#table_drugs").append("<tr><td>"
+ $("#drugs_list").val() + "<input type='text' name='past_druges_used' value="+$("#drugs_list").val()+">"
+ "</td><td>" + $("#drugs-explain").val()+"<input type='text' name='how_to_use' value="+$("#drugs-explain").val()+">"
+ "</td><td>" + "<button type='button' class='col-sm-7 btn btn-danger pull-right'>delete</button> "
+ "</td></tr>");
And my html:
<div class="col-md-12">
<div id="drugs_list_div" class="form-group">
<div class="col-md-4 col-md-offset-6">
<select id="drugs_list" class="form-control" style="font-family: font-style-3;">
<option>empty</option>
<option>Drugs 1</option>
<option>Drugs 3</option>
<option>Drugs 2</option>
</select>
</div>
</div>
<div id="drugs-explain-div" class="form-group">
<div class="col-md-4 col-md-offset-6">
<input type="text" class="form-control" id="drugs-explain" style="font-family: font-style-1;">
</div>
</div>
</div>
<div class="col-md-12">
<div id="table-drugs-div" class="col-xs-11 list-hide">
<table class="table table-striped" id="table_drugs">
</table>
</div>
</div>
You need to put quotes around your values:
$("#table_drugs").append("<tr><td>"
+ $("#drugs_list").val() + "<input type='text' name='past_druges_used' value='"+$("#drugs_list").val()+"'>"
+ "</td><td>" + $("#drugs-explain").val()+"<input type='text' name='how_to_use' value='"+$("#drugs-explain").val()+"'>"
+ "</td><td>" + "<button type='button' class='col-sm-7 btn btn-danger pull-right'>delete</button> "
+ "</td></tr>");