How to show text box in html which is declared in JavaScript - javascript

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>

Related

How I can maintain the sequence of beneficiaries generated with jquery?

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

How to prevent append from key in button to not add extra values when a new div is created

I've created a form which will add products to be key in details of the said products, each products will sometime have serialnumbers, users will need to click enabled serial numbers to start key in serial numbers.
So i have issue here whereby, when i add a new product, and key in serial number on product #1, it will have additional value added to it.
in a more detailed and simpler explanation;
Add Product -> product #2 created.
enabled product #1 table to key in
value inputted to textarea became
SGH983819;
;
How do i go about to not let any previous product's key in not add on those ;\n in any previous appended section?
$(document).ready(function() {
function enableSerial() {
$('.enable-serial').on('change', function() {
var item = $(this).data('item');
$('.enable-' + item).prop('disabled', !this.checked);
});
}
$('#add_product').on('click', function() {
var itemNo = $('.product-item').length + 1;
var appendData = '<div class="product-item" data-item="' + itemNo +'">' +
'<span>#' + itemNo +'</span>' +
'<button type="button" class="btn btn-danger float-right remove_product"><i class="fas fa-trash-alt"></i></button>' +
'<div class="form-group row">' +
'<label class="col-sm-2 col-form-label font-weight-bold">Category</label>' +
'<div class="col-sm-2">' +
'<input class="form-control" name="products[' + (itemNo - 1) + ']category" type="text" placeholder="eg. 333" maxlength="3"required>' +
'</div>' +
'<label class="col-sm-1 col-form-label font-weight-bold">Code</label>' +
'<div class="col-sm-2">' +
'<input class="form-control" name="products[' + (itemNo - 1) + ']code" type="text" placeholder="eg. 22" maxlength="2" required>' +
'</div>' +
'<label class="col-sm-1 col-form-label font-weight-bold">Partnumber</label>' +
'<div class="col-sm-2">' +
'<input class="form-control" name="products[' + (itemNo - 1) + ']partnumber" type="text" placeholder="eg. NGH92838" required>' +
'</div>' +
'</div>' +
'<div class="form-group row">' +
'<label class="col-sm-2 col-form-label font-weight-bold">Brand</label>' +
'<div class="col-sm-2">' +
'<input class="form-control" name="products[' + (itemNo - 1) + ']brand" type="text" placeholder="eg. Rototype" required>' +
'</div>' +
'<label class="col-sm-1 col-form-label font-weight-bold">Quantities</label>' +
'<div class="col-sm-2">' +
'<input class="form-control" name="products[' + (itemNo - 1) + ']qty" type="number" placeholder="eg. 1" required>' +
'</div>' +
'<label class="col-sm-1 col-form-label font-weight-bold">Location</label>' +
'<div class="col-sm-2">' +
'<input class="form-control location-ctrl-' + itemNo +' location-ctrl" data-item="' + itemNo +'" type="text" name="products[' + (itemNo - 1) + ']loc_name" list="locations" value="">' +
'<input type="hidden" class="location-id-' + itemNo +'" name="products[' + (itemNo - 1) + ']location_id" value="">' +
'<input type="hidden" class="loc-desc-' + itemNo +'" name="products[' + (itemNo - 1) + ']loc_desc" value="">' +
'</div>' +
'</div>' +
'<div class="form-group row">' +
'<label class="col-sm-2 col-form-label font-weight-bold">Description</label>' +
'<div class="col-sm-8">' +
'<input class="form-control" name="products[0]description" type="text" placeholder="eg. Spare part for CSD2002">' +
'</div>' +
'</div>' +
'<div class="form-group row">' +
'<label class="col-sm-2 col-form-label font-weight-bold">Serial Number(s)</label>' +
'<div class="col-sm-5">' +
'<input class="form-control enable-' + itemNo +' serial-' + itemNo +'" maxlength="25" placeholder="Key in Serial Number and hit button Key In" disabled>' +
'</div>' +
'<div class="col-sm-5">' +
'<button class="btn btn-dark enable-' + itemNo +' keyin-ctrl-' + itemNo +' keyin-ctrl" data-item="' + itemNo +'" type="button" disabled>Key In</button>' +
'<button class="btn btn-dark ml-1 enable-' + itemNo +' undo-ctrl-' + itemNo +' undo-ctrl" data-item="' + itemNo +'" type="button" disabled>Del</button>' +
'<input class="form-check-input ml-4 mt-2 pointer enable-serial-' + itemNo +' enable-serial" data-item="'+ itemNo +'" id="checkbox-' + itemNo +'" type="checkbox">' +
'<label class="form-check-label ml-5 pointer" for="checkbox-' + itemNo +'">tick to enable serialnumber</label>' +
'</div>' +
'</div>' +
'<div class="form-group row">' +
'<label class="col-sm-2 col-form-label"></label>' +
'<div class="col-sm-5">' +
'<textarea class="form-control display-' + itemNo +'" name="products[' + (itemNo - 1) + ']serialnumbers" rows="5" style="resize: none;" placeholder="eg. SGH8484848" readonly></textarea>' +
'</div>' +
'</div>' +
'<hr>' +
'</div>';
$('#append').append(appendData);
enableSerial();
ctrlSerial();
});
function ctrlSerial() {
$('.keyin-ctrl').on('click', function() {
var item = $(this).data('item');
var result = $('.serial-' + item).val() + '; \n';
$('.display-' + item).append(result);
$('.serial-' + item).val('').focus();
});
$('.undo-ctrl').on('click', function() {
var item = $(this).data('item');
$('.display-' + item).html('');
});
}
$('#append').on('click','.remove_product', function(){
var itemNo = $('.product-item').length + 1;
$(this).parent('div').remove();
itemNo--;
});
enableSerial();
ctrlSerial();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="shadow border">
<h4>Product Details</h4>
<hr>
<h5>GRN Details</h5>
<form method="post" action="">
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">GRN</label>
<div class="col-sm-4">
<input class="form-control" type="text" value="020719" name="nnmmyy" readonly>
<input type="hidden" name="supp_name" value="ABCD Co. Ltd.">
<input type="hidden" name="supp_do" value="DO97/39901/01">
<input type="hidden" name="do_date" value="17/07/2019">
</div>
</div>
<!-- Multiple Product addition -->
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">Product Setting</label><br/>
<div class="col-sm-5">
<button type="button" id="add_product" class="btn btn-dark">Add Product <i class="fas fa-plus-square"></i></button>
</div>
</div>
<hr>
<!-- Frist Group -->
<div class="product" id="append">
<!-- Product Details -->
<div class="product-item" data-item="1">
<span>#1</span>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">Category</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]category" type="text" placeholder="eg. 333" maxlength="3"required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">Code</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]code" type="text" placeholder="eg. 22" maxlength="2" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">Partnumber</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]partnumber" type="text" placeholder="eg. NGH92838" required>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">Brand</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]brand" type="text" placeholder="eg. Rototype" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">Quantities</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]qty" type="number" placeholder="eg. 1" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">Location</label>
<div class="col-sm-2">
<input class="form-control location-ctrl-1 location-ctrl" data-item="1" type="text" name="products[0]loc_name" list="locations" value="">
<input type="hidden" class="location_id-1" name="products[0]location_id" value="">
<input type="hidden" class="loc_desc-1" name="products[0]loc_desc" value="">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">Description</label>
<div class="col-sm-8">
<input class="form-control" name="products[0]description" type="text" placeholder="eg. Spare part for CSD2002">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">Serial Number(s)</label>
<div class="col-sm-5">
<input class="form-control enable-1 serial-1" maxlength="25" placeholder="Key in Serial Number and hit button Key In" disabled>
</div>
<div class="col-sm-5">
<button class="btn btn-dark enable-1 keyin-ctrl-1 keyin-ctrl" data-item="1" type="button" disabled>Key In</button>
<button class="btn btn-dark enable-1 undo-ctrl-1 undo-ctrl" data-item="1" type="button" disabled>Del</button>
<input class="form-check-input ml-4 mt-2 pointer enable-serial-1 enable-serial" data-item="1" id="checkbox-1" type="checkbox">
<label class="form-check-label ml-5 pointer" for="checkbox-1">tick to enable serialnumber</label>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-5">
<textarea class="form-control display-1" name="products[0]serialnumbers" rows="5" style="resize: none;" placeholder="eg. SGH8484848" readonly></textarea>
</div>
</div>
<hr>
</div>
<!-- append start -->
</div>
<datalist id="locations">
<option value="A0001" data-locationid="1" data-locdesc="Cabinet A"></option>
</datalist>
</form>
</main>
I in hope that there some suggestion or way to do it whereby wont have additional value added when keying previous product serial numbers
found my own fix...
added result.val(''); will reset any key in
function ctrlSerial() {
$('.keyin-ctrl').on('click', function() {
var item = $(this).data('item');
var result = $('.serial-' + item).val() + '; \n';
$('.display-' + item).append(result);
$('.serial-' + item).val('').focus();
result.val(''); // added this to also wipe clean properly
});
$('.undo-ctrl').on('click', function() {
var item = $(this).data('item');
$('.display-' + item).html('');
});
}

Addition On javascript Not working when new row is added

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>

how to use closest with selection div

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

Cant' put number in value of text input using jquery

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>");

Categories

Resources