How to get values of dynamic id in Javascript? - javascript

As i'm new to javascript i'm struggling to to get input values of dynamically generated id.
var i = 0;
function addRow() {
var div = document.createElement('div');
div.className = 'rTableRow';
div.id = 'Taxrow' + i;
div.innerHTML =
'<div class="rTableCell"><input type="text" name="product'+i+'" id="product'+i+'" placeholder="Product Name"></div>\
<div class="rTableCell"><input type="text" name="price'+i+'" id="price'+i+'" placeholder="Item Price"></div>\
<div class="rTableCell"><input type="text" name="qty'+i+'" id="qty'+i+'" onchange="subTotal();" placeholder="Item Quantity"></div>\
<div class="rTableCell"><input type="text" name="tax'+i+'" id="tax'+i+'" onkeyup="Total();" placeholder="Tax Percentage"></div>\
<div class="rTableCell"><input name="subtotal'+i+'" type="text" id="subtotal'+i+'" size="10" disabled></div>\
<div class="rTableCell"><input name="salestax'+i+'" type="text" id="salestax'+i+'" size="10" disabled></div>\
<div class="rTableCell"><input name="gtotal'+i+'" type="text" id="gtotal'+i+'" size="10" disabled></div>\
<input type="button" value="-" onclick="removeRow(this)">';
document.getElementById('dyncalc').appendChild(div);
i=i+1;
}
function removeRow(input) {
document.getElementById('dyncalc').removeChild(input.parentNode);
}
/*
function setValue(node){
var price = document.getElementById(node.value).value;
//alert(price);
}​
*/
function subTotal() {
/* var price = document.getElementById('price[i]').value;
var qty = document.getElementById('qty[i]').value;*/
var price = document.TaxCalculator.price.value;
var qty = document.TaxCalculator.qty.value;
var productPrice = price * qty;
document.TaxCalculator.subtotal.value = productPrice.toFixed(2);
return productPrice;
}
function Total() {
var subtotal = subTotal();
var stax = (document.TaxCalculator.tax.value) / 100 ;
tax = subtotal * stax ;
document.TaxCalculator.subtotal.value = subtotal.toFixed(2);
document.TaxCalculator.salestax.value = tax.toFixed(2);
var gtotal = subtotal + tax;
document.TaxCalculator.gtotal.value = gtotal.toFixed(2);
}
.taxCalculator h3{
text-align: center;
text-transform: uppercase;
padding: 10px;
color: #ffffff;
}
.rTable { display: table; }
.rTableRow { display: table-row; }
.rTableHeading { display: table-header-group; }
.rTableBody { display: table-row-group; }
.rTableFoot { display: table-footer-group; }
.rTableCell, .rTableHead { display: table-cell; }
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Tax Calculator</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body>
<div class="taxCalculator">
<div class="container">
<p></p>
<div class="card">
<h3 style="text-align: center;" class="card-header bg-info">Tax Caluculator </h3>
<p></p>
<div class="form-group d-flex justify-content-center">
<form action="" name="TaxCalculator" id="TaxCalculator" class="form-inline">
<div class="rTable" id="dyncalc">
<div class="rTableRow">
<div class="rTableHead"><input type="button" class="btn btn-info" value="AddItems" onclick="addRow()"></div>
</div>
<div class="rTableRow">
<div class="rTableHead"><label for="product" >Product Name</label></div>
<div class="rTableHead"><label for="price" >Price</label></div>
<div class="rTableHead"><label for="qty" >Item Qty</label></div>
<div class="rTableHead"><label for="tax" >Tax Percentage (%) </label></div>
<div class="rTableHead"><label for="subtotal" >Sub Total: </label></div>
<div class="rTableHead"><label for="salestax" >Tax :</label></div>
<div class="rTableHead"><label for="gtotal" >Grand Total: </label></div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
I want to get the input values of Taxrow[i] id . I tired onchange and var price = document.TaxCalculator.price[i].value; I know, I made something wrong.
and also I used document.getElementById(node.value).value using onchange(getValue.this)
help me to achieve this.

You can make the functions Total and Subtotal have a parameter : Total(i) . Then generate the html to call the functions like this :
div.innerHTML =
'<div class="rTableCell"><input type="text" name="product'+i+'" id="product'+i+'" placeholder="Product Name"></div>\
<div class="rTableCell"><input type="text" name="price'+i+'" id="price'+i+'" placeholder="Item Price"></div>\
<div class="rTableCell"><input type="text" name="qty'+i+'" id="qty'+i+'" onchange="subTotal('+ i +');" placeholder="Item Quantity"></div>\
<div class="rTableCell"><input type="text" name="tax'+i+'" id="tax'+i+'" onkeyup="Total('+ i +');" placeholder="Tax Percentage"></div>\
<div class="rTableCell"><input name="subtotal'+i+'" type="text" id="subtotal'+i+'" size="10" disabled></div>\
<div class="rTableCell"><input name="salestax'+i+'" type="text" id="salestax'+i+'" size="10" disabled></div>\
<div class="rTableCell"><input name="gtotal'+i+'" type="text" id="gtotal'+i+'" size="10" disabled></div>\
<input type="button" value="-" onclick="removeRow(this)">';

Related

javascript basic calculation price,quantity and discount

I would like to count price and discount and quantity for result which is the total. Is it possible to do with javascript and how? I have tried several ways to implement the function in javascript however none of my effort works.
<body style="background-image: linear-gradient(to right, seagreen , lightyellow");>
<div class="container-fluid">
<div class="row">
<div class="col-lg-3">
<div class="card">
<div class="card-body">
<div class="form-group col-lg-12 col-md-12 col-sm-12">
<div>
<label>Customer Name:</label>
<input type="text" class="form-control" id="cname" name="customername" />
</div>
<div>
<label>Test Rate:</label>
<input type="number" class="form-control calculationadd" id="testprice" name="testamt" />
</div>
<div>
<label>Quantity:</label>
<input type="number" class="form-control calculationadd" id="qty" name="qtyname" />
</div>
<div>
<label>Discount%:</label>
<input type="number" class="form-control calculationadd" id="discountid" name="dis" />
</div>
<div>
<label>Total:</label>
<input type="number" class="form-control calculationadd" id="totalid" name="total" />
</div>
<script>
$(".calculationadd").keyup(function () {
var customername = $("#cname").val();
var testamt = $("#testprice").val();
var quan = $("#qty").val();
var dis = $("#discountid").val();
var total = $("#totalid").val();
var rateqty = parseFloat(testamt) * parseFloat(quan);
var afterdiscount = parseFloat(rateqty) * parseFloat(dis) / (100)
var final = parseFloat(rateqty) - parseFloat(afterdiscount);
$("#totalid").val(rateqty);
}
);
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</body>

How to add 2 new input from 1 button?

Hi i have my code here where now i would like 1 button click to add a input box to contact Name and contact No
Example of image when user click on the add more field
Currently what i have is 2 different input fields where i have hidden the button for the contact No:
Originally i am allow to press on the 2 button to display a newinput but now i would like that 1 button input appear for each new input for contact name and contact no how can i combine it?
Here my code snippet for the code
// Script on create a new input box 1 for Contact: Name
const $container1 = $('#contactContainername')
$(".remove1").eq(0).hide()
$container1.on('click', ".no", function(e) {
const add1 = $(this).is(".add1")
const $input1 = $container1.find(".contactname");
const len1 = $input1.length;
if (add1) {
const $newInput1 = $input1.eq(0).clone(true)
$newInput1.find("[name=contactname]")
.attr("id", `new_${$input1.length}`)
.val("");
$container1.append($newInput1);
$newInput1.find(".add1").remove()
$newInput1.find(".remove1").show()
// $newPhone.find(".add").hide(len>0)
} else {
$(this).closest(".contactname").remove()
}
})
// Script on create a new input box 2 for Contact: No
const $container = $('#contactContainer')
$(".remove").eq(0).hide()
$container.on('click', ".ar", function(e) {
const add = $(this).is(".add");
const $input = $container.find(".contact");
const len = $input.length;
if (add) {
const $newInput = $input.eq(0).clone(true)
$newInput.find("[name=contact]")
.attr("id", `new_${$input.length}`)
.val("");
$container.append($newInput);
$newInput.find(".add").remove()
$newInput.find(".remove").show()
// $newPhone.find(".add").hide(len>0)
} else {
$(this).closest(".contact").remove()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact Name:</label>
<div class="col-4" id="contactContainername">
<div class="flex contactname" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontactname" name="contactname" type="text" class="form-control" placeholder="Name" required>
<input type="button" class="no add1" value="Add More Field" style="cursor: pointer;">
<span class="no remove1"><label style="cursor: pointer; padding-top: 5px;"><i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span>
</div>
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact No:</label>
<div class="col-4" id="contactContainer">
<div class="flex contact" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontact" name="contact" type="text" class="form-control" placeholder="9343****" pattern="\b\d{8}\b" required>
<input type="button" class="ar add" value="Add More Field" style="cursor: pointer;" hidden>
<!-- <span class="ar add"><label style="cursor: pointer; padding-top: 5px;"><i data-feather="plus" ></i></label></span> -->
<span class="ar remove"><label style="cursor: pointer; padding-top: 5px;"><i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span>
</div>
</div>
</div>
I've just changed your code,I've added onclick event to add more field button
function addMoreField() {
const $contactContainername = $('#contactContainername');
const $contactContainerNo = $('#contactContainer');
const $contactNameinput = $contactContainername.find(".contactname");
const $contactNoInput = $contactContainerNo.find(".contact");
const $newContactNameinput = $contactNameinput.eq(0).clone(true);
$newContactNameinput.find("[name=contactname]")
.attr("id", `contactNameInput_${$contactNameinput.length}`)
.val("");
$newContactNameinput.attr("id", `contactName_${$contactNameinput.length}`);
const removeButton = $newContactNameinput.find(".removeButton");
removeButton.attr("onclick", `removeField(${$contactNameinput.length})`);
removeButton.show();
const $newContactNoinput = $contactNoInput.eq(0).clone(true);
$newContactNoinput.attr("id", `contactNo_${$contactNameinput.length}`);
$newContactNoinput.find("[name=contact]")
.attr("id", `contactNoInput_${$contactNoInput.length}`)
.val("");
$contactContainername.append($newContactNameinput);
$contactContainerNo.append($newContactNoinput);
}
function removeField(id) {
if (id === 0) return;
const $contactContainername = $('#contactContainername');
const $contactContainerNo = $('#contactContainer');
const $contactNameinput = $contactContainername.find(`#contactName_${id}`);
const $contactNoinput = $contactContainerNo.find(`#contactNo_${id}`);
$contactNameinput.remove();
$contactNoinput.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" onclick='addMoreField()' class="no add1" value="Add More Field" style="cursor: pointer;">
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact Name:</label>
<div class="col-4" id="contactContainername">
<div id="contactName_0" class="flex contactname" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontactname" name="contactname" type="text" class="form-control" placeholder="Name" required>
<input class="removeButton" type="button" onclick='removeField(0)' value="Remove" style="cursor: pointer;display:none">
</div>
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact No:</label>
<div class="col-4" id="contactContainer">
<div id="contactNo_0" class="flex contact" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontact" name="contact" type="text" class="form-control" placeholder="9343****" pattern="\b\d{8}\b" required>
<input type="button" class="ar add" value="Add More Field" style="cursor: pointer;" hidden>
<!-- <span class="ar add"><label style="cursor: pointer; padding-top: 5px;"><i data-feather="plus" ></i></label></span> -->
<span class="ar remove"><label style="cursor: pointer; padding-top: 5px;"><i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span>
</div>
</div>
</div>

dynamically adding summernote editor not working

I'm trying to adding summernote editor dynamically whenever clicking on add button.
It doesn't working while adding through of dynamically.
Here is my code.
$(document).ready(function() {
var maxField = 20; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div class="row"><div class="col-md-6"><div class="form-group"><label for="profile_img_dynamic">Heading Image</label><div class="custom-file"><input type="file" class="custom-file-input" id="profile_img_dynamic" name="profile_img_dynamic[]" required><label class="custom-file-label" for="customFile">Choose file</label></div></div></div><div class="col-md-6"><div class="form-group"><label for="title_name_dynamic">Heading Title</label><input type="text" name="title_name_dynamic[]" class="form-control" id="title_name_dynamic" placeholder="Enter name"></div></div><div class="col-md-10"><!-- /.card-header --><div class="card-body pad"><div class="mb-3"><label for="description">Descriptions</label><textarea class="textarea" name="info_name_dynamic[]" id="info_name_dynamic" rows="3" placeholder="Place some text here"style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea></div></div></div>Remove Me</i></div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').empty(); //Remove field html
x--; //Decrement field counter
});
});
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.7.0/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.7.0/summernote.js"></script>
<div class="field_wrapper">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="profile_img_dynamic">Heading Image</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="profile_img_dynamic" name="profile_img_dynamic[]" required>
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="title_name_dynamic">Heading Title</label>
<input type="text" name="title_name_dynamic[]" class="form-control" id="title_name_dynamic" placeholder="Enter name">
</div>
</div>
<div class="col-md-10">
<!-- /.card-header -->
<div class="card-body pad">
<div class="mb-3">
<label for="description">Descriptions</label>
<textarea class="textarea" name="info_name_dynamic[]" id="info_name_dynamic" rows="3" placeholder="Place some text here"
style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea>
</div>
</div>
</div>
<div class=""></div>
<div class="col-md-2">
<div class="form-group">
<label for="add">Add More</label><br>
ADD</i>
</div>
</div>
</div>
</div>
As you can see, summer editor not does not displaying there is only simple textarea are displaying instead of editor.
You can add $(wrapper).find('.textarea').summernote() after $(wrapper).append(fieldHTML);
$(wrapper).append(fieldHTML); //Add field html
$(wrapper).find('.textarea').summernote()
Demo
$(document).ready(function() {
var maxField = 20; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div class="row"><div class="col-md-6"><div class="form-group"><label for="profile_img_dynamic">Heading Image</label><div class="custom-file"><input type="file" class="custom-file-input" id="profile_img_dynamic" name="profile_img_dynamic[]" required><label class="custom-file-label" for="customFile">Choose file</label></div></div></div><div class="col-md-6"><div class="form-group"><label for="title_name_dynamic">Heading Title</label><input type="text" name="title_name_dynamic[]" class="form-control" id="title_name_dynamic" placeholder="Enter name"></div></div><div class="col-md-10"><!-- /.card-header --><div class="card-body pad"><div class="mb-3"><label for="description">Descriptions</label><textarea class="textarea" name="info_name_dynamic[]" id="info_name_dynamic" rows="3" placeholder="Place some text here"style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea></div></div></div>Remove Me</i></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(document).ready(function() {
$('.textarea').summernote();
});
//Once add button is clicked
$(addButton).click(function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
$(wrapper).find('.textarea').summernote()
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').empty(); //Remove field html
x--; //Decrement field counter
});
});
<!-- include libraries(jQuery, bootstrap) -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<!-- include summernote css/js -->
<link href="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote.min.js"></script>
<div class="field_wrapper">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="profile_img_dynamic">Heading Image</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="profile_img_dynamic" name="profile_img_dynamic[]" required>
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="title_name_dynamic">Heading Title</label>
<input type="text" name="title_name_dynamic[]" class="form-control" id="title_name_dynamic" placeholder="Enter name">
</div>
</div>
<div class="col-md-10">
<!-- /.card-header -->
<div class="card-body pad">
<div class="mb-3">
<label for="description">Descriptions</label>
<textarea class="textarea" name="info_name_dynamic[]" id="info_name_dynamic" rows="3" placeholder="Place some text here" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea>
</div>
</div>
</div>
<div class=""></div>
<div class="col-md-2">
<div class="form-group">
<label for="add">Add More</label><br>
ADD</i>
</div>
</div>
</div>
</div>

why dynamically added fields not removing by clicking remove button?

here is my code,
while adding input field by clicking add button so field will appear but after trying to remove those fields by removing button so it is not working.
$(document).ready(function() {
//#naresh action dynamic childs
var next = 0;
$("#add-more").click(function(e) {
e.preventDefault();
var addto = "#field" + next;
var addRemove = "#field" + (next);
next = next + 1;
var newIn = ' <div id="field' + next + '" name="field' + next + '"><!-- Text input--> <div class="form-group"> <div class="col-6"> <label for="vat" ></label><input type="text" placeholder="Check In Date" id="datepicker-12" name="PeriodFrom[]" class=" datepicker_recurring_start" value=""></div><div class="col-6"><label for="street" ></label><input type="text" name="PeriodTo[]" placeholder="Check Out Date" class=" datepicker_recurring_start" value=""></div></div><div class="form-group"><div class="col-6"><label for="vat" ></label><input type="text" id="DoubleBad" name="DoubleBad" placeholder="Double Bed" value=""></div><div class="col-6"><label for="street" ></label><input type="text" placeholder="Above 12 Years" id="EXTRA_ADL_ABOVE_12_YRS" name="EXTRA_ADL_ABOVE_12_YRS" value=""></div></div><div class=" form-group"> <label for="postal-code" > </label><label for="postal-code" ></label><input type="text" id="CNB" name="MaxCNB[]" value="" required="required" placeholder="Max Rate CNB"> </div> </div>';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >Remove</button></div></div><div id="field">';
var removeButton = $(removeBtn);
$(addto).after(newInput);
$(addRemove).after(removeButton);
$("#field" + next).attr('data-source', $(addto).attr('data-source'));
$("#count").val(next);
$('body').on('click', '.remove-me', function(e) {
e.preventDefault();
var fieldNum = this.id.charAt(this.id.length - 1);
var fieldID = "#field" + fieldNum;
$(this).remove();
$(fieldID).remove();
});
});
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.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://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="right-panel" class="right-panel">
<div class="content mt-3" >
<div class="animated fadeIn">
<div class="row" style="border:none;">
<div class="col-md-12">
<div class="card" >
<div class="card-header">
<div class="row" >
<i class="fa fa-hotel" style="font-size:24px;"></i>
<h4 style=" font-family: 'Ubuntu',sans-serif;margin-left:20px;"> Manage Hotels </h4>
</div>
</div>
<div class="card-body">
<form method="post" action="<?php echo base_url(); ?>Admin/Insert-Hotels">
<div class="card-body card-block">
<div class="form-group">
<div class="col-6" id="content">
<label for="vat" ></label><input type="text" id="datepicker_recurring_start" name="PeriodFrom[]" class=" datepicker_recurring_start" placeholder="Check In Date" value="" required="required">
</div>
<div class="col-6" id="content">
<label for="street" ></label><input type="text" id="datepicker-13" name="PeriodTo[]" class=" datepicker_recurring_start" placeholder="Check Out Date" value="" required="required">
</div>
</div>
<div class=" form-group">
<div class="col-6">
<label for="vat" ></label><input type="text" id="DoubleBed" name="MaxDoubleBed[]" value="" placeholder="Max Rate Double Bed" required="required">
</div>
<div class="col-6">
<label for="postal-code" ></label><input type="text" id="SigleBed" name="MaxSigleBad[]" value="" placeholder="Max Rate Sigle Bed" required="required">
</div>
</div>
<div class=" form-group">
<div class="col-6">
<label for="postal-code" ></label><input type="text" id="CNB" name="MaxCNB[]" value="" required="required" placeholder="Max Rate CNB">
</div>
<div class="col-6">
<label for="postal-code" ></label>
<select name="cityID" id="cityID" class="-md " required="required">
<option value="">Select Country and City</option>
<?php
foreach ($fatch_hotels_country as $key => $fatch_hotels_country) {
echo "<option value='".$fatch_hotels_country->id."'>".$fatch_hotels_country->citiesName."</option>";
}
?>
</select>
</div>
</div>
<div class=" form-group">
<label for="postal-code" ></label>
<label for="company" ></label><input type="text" id="HotelName" name="Star" value="" required="required" placeholder="Star">
</div>
</div>
<!----------------------------------- Add More Data Start -------------------------->
<div class=" form-group">
<div id="field">
<div id="field0">
</div>
</div >
<!----------------------------------- Add More Data End -------------------------->
</div>
</div>
<div class="modal-footer">
<input type="reset" class="btn btn-danger" value="Reset">
<input type="submit" class="btn btn-primary" value="Insert">
<button id="add-more" name="add-more" class="btn btn-primary">Add More</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
here you can see,
I'm trying to add input fields by clicking "add more" button right below right side.
while fields are displaying you can see "remove" button right top of dynamically added input fields.
while clicking on that button so those fields are not remove.
It seems the div id to be removed is getting wrong so
Change
var fieldNum = this.id.charAt(this.id.length - 1);
var fieldID = "#field" + fieldNum;
to
var fieldNum = +this.id.charAt(this.id.length - 1);
var fieldID = "#field" + parseFloat(fieldNum + 1);
and Add
next = fieldNum;
in $('body').on('click', '.remove-me', function(e) {
DEMO HERE
Try this
$(document).ready(function() {
//#naresh action dynamic childs
var next = 0;
$("#add-more").click(function(e) {
e.preventDefault();
var addto = "#field" + next;
var addRemove = "#field" + (next);
next = next + 1;
var newIn = ' <div id="field' + next + '" name="field' + next + '"><!-- Text input--> <div class="form-group"> <div class="col-6"> <label for="vat" ></label><input type="text" placeholder="Check In Date" id="datepicker-12" name="PeriodFrom[]" class=" datepicker_recurring_start" value=""></div><div class="col-6"><label for="street" ></label><input type="text" name="PeriodTo[]" placeholder="Check Out Date" class=" datepicker_recurring_start" value=""></div></div><div class="form-group"><div class="col-6"><label for="vat" ></label><input type="text" id="DoubleBad" name="DoubleBad" placeholder="Double Bed" value=""></div><div class="col-6"><label for="street" ></label><input type="text" placeholder="Above 12 Years" id="EXTRA_ADL_ABOVE_12_YRS" name="EXTRA_ADL_ABOVE_12_YRS" value=""></div></div><div class=" form-group"> <label for="postal-code" > </label><label for="postal-code" ></label><input type="text" id="CNB" name="MaxCNB[]" value="" required="required" placeholder="Max Rate CNB"> </div> </div>';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >Remove</button></div></div><div id="field">';
var removeButton = $(removeBtn);
$(addto).after(newInput);
$(addRemove).after(removeButton);
$("#field" + next).attr('data-source', $(addto).attr('data-source'));
$("#count").val(next);
});
$(document).on('click', '.remove-me', function(e) {
e.preventDefault();
var fieldNum = this.id.charAt(this.id.length - 1);
var fieldID = "#field" + fieldNum;
$(this).remove();
$(fieldID).remove();
});
});
<html><head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script><style type="text/css">.as-console-wrapper { position: fixed; bottom: 0; left: 0; right: 0; max-height: 150px; overflow-y: scroll; overflow-x: hidden; border-top: 1px solid #000; display: none; }
.as-console { background: #e9e9e9; border: 1px solid #ccc; display: table; width: 100%; border-collapse: collapse; }
.as-console-row { display: table-row; font-family: monospace; font-size: 13px; }
.as-console-row:after { display: table-cell; padding: 3px 6px; color: rgba(0,0,0,.35); border: 1px solid #ccc; content: attr(data-date); vertical-align: top; }
.as-console-row + .as-console-row > * { border: 1px solid #ccc; }
.as-console-row-code { width: 100%; white-space: pre-wrap; padding: 3px 5px; display: table-cell; font-family: monospace; font-size: 13px; vertical-align: middle; }
.as-console-error:before { content: 'Error: '; color: #f00; }
.as-console-assert:before { content: 'Assertion failed: '; color: #f00; }
.as-console-info:before { content: 'Info: '; color: #00f; }
.as-console-warning:before { content: 'Warning: '; color: #e90 }
#-webkit-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
#-moz-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
#-ms-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
#keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
.as-console-row-code, .as-console-row:after { -webkit-animation: flash 1s; -moz-animation: flash 1s; -ms-animation: flash 1s; animation: flash 1s; }</style>
</head>
<body>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.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://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="right-panel" class="right-panel">
<div class="content mt-3">
<div class="animated fadeIn">
<div class="row" style="border:none;">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<div class="row">
<i class="fa fa-hotel" style="font-size:24px;"></i>
<h4 style=" font-family: 'Ubuntu',sans-serif;margin-left:20px;"> Manage Hotels </h4>
</div>
</div>
<div class="card-body">
<form method="post" action="<?php echo base_url(); ?>Admin/Insert-Hotels">
<div class="card-body card-block">
<div class="form-group">
<div class="col-6" id="content">
<label for="vat"></label><input type="text" id="datepicker_recurring_start" name="PeriodFrom[]" class=" datepicker_recurring_start" placeholder="Check In Date" value="" required="required">
</div>
<div class="col-6" id="content">
<label for="street"></label><input type="text" id="datepicker-13" name="PeriodTo[]" class=" datepicker_recurring_start" placeholder="Check Out Date" value="" required="required">
</div>
</div>
<div class=" form-group">
<div class="col-6">
<label for="vat"></label><input type="text" id="DoubleBed" name="MaxDoubleBed[]" value="" placeholder="Max Rate Double Bed" required="required">
</div>
<div class="col-6">
<label for="postal-code"></label><input type="text" id="SigleBed" name="MaxSigleBad[]" value="" placeholder="Max Rate Sigle Bed" required="required">
</div>
</div>
<div class=" form-group">
<div class="col-6">
<label for="postal-code"></label><input type="text" id="CNB" name="MaxCNB[]" value="" required="required" placeholder="Max Rate CNB">
</div>
<div class="col-6">
<label for="postal-code"></label>
<select name="cityID" id="cityID" class="-md " required="required">
<option value="">Select Country and City</option>
<!--?php
foreach ($fatch_hotels_country as $key =--> $fatch_hotels_country) {
echo "<option value="".$fatch_hotels_country->id."">".$fatch_hotels_country->citiesName."</option>";
}
?>
</select>
</div>
</div>
<div class=" form-group">
<label for="postal-code"></label>
<label for="company"></label><input type="text" id="HotelName" name="Star" value="" required="required" placeholder="Star">
</div>
</div>
<!----------------------------------- Add More Data Start -------------------------->
<div class=" form-group">
<div id="field">
<div id="field0">
</div>
</div>
<!----------------------------------- Add More Data End -------------------------->
</div>
</form></div>
<div class="modal-footer">
<input type="reset" class="btn btn-danger" value="Reset">
<input type="submit" class="btn btn-primary" value="Insert">
<button id="add-more" name="add-more" class="btn btn-primary">Add More</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
//#naresh action dynamic childs
var next = 0;
$("#add-more").click(function(e) {
e.preventDefault();
var addto = "#field" + next;
var addRemove = "#field" + (next);
next = next + 1;
var newIn = ' <div id="field' + next + '" name="field' + next + '"><!-- Text input--> <div class="form-group"> <div class="col-6"> <label for="vat" ></label><input type="text" placeholder="Check In Date" id="datepicker-12" name="PeriodFrom[]" class=" datepicker_recurring_start" value=""></div><div class="col-6"><label for="street" ></label><input type="text" name="PeriodTo[]" placeholder="Check Out Date" class=" datepicker_recurring_start" value=""></div></div><div class="form-group"><div class="col-6"><label for="vat" ></label><input type="text" id="DoubleBad" name="DoubleBad" placeholder="Double Bed" value=""></div><div class="col-6"><label for="street" ></label><input type="text" placeholder="Above 12 Years" id="EXTRA_ADL_ABOVE_12_YRS" name="EXTRA_ADL_ABOVE_12_YRS" value=""></div></div><div class=" form-group"> <label for="postal-code" > </label><label for="postal-code" ></label><input type="text" id="CNB" name="MaxCNB[]" value="" required="required" placeholder="Max Rate CNB"> </div> </div>';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >Remove</button></div></div><div class="field"></div>';
var removeButton = $(removeBtn);
$(addto).after(newInput);
$(addRemove).after(removeButton);
$("#field" + next).attr('data-source', $(addto).attr('data-source'));
$("#count").val(next);
$('body').on('click', '.remove-me', function(e) {
e.preventDefault();
var fieldNum = parseInt(this.id.charAt(this.id.length - 1))+1;
var fieldID = "#field" + fieldNum;
$(this).remove();
$(fieldID).remove();
});
});
});
</script>
<div class="as-console-wrapper"><div class="as-console"></div></div></body></html>

How to save Dynamically Generated table rows to database

This is My HTML Code
<form method="POST" action="backend/backup.php">
<div class="box-body col-sm-12">
<input type="hidden" name="txtSlNo" id="txtSlNo" value="1">
<div class="col-sm-2">
<label for="Date" class="control-label">Date:</label>
<input type="text" class="text-right" name="date[]" id="date"
value="<?php echo date(" Y/M/D ")?>">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Amount:</label>
<input type="text" size="7" class="text-right" name="txtAmount[]"
id="txtAmount" oninput="calculate()" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Unit:</label>
<input type="text" size="7" name="txtUnit[]" class="text-right"
id="txtUnit" oninput="calculate()" value="1" onkeypress="return
isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Total:</label>
<input type="text" size="7" name="txtTotal[]" class="text-right"
id="txtTotal" oninput="calculate();" oninput="addTotal();" readonly>
</div>
<div class="col-sm-2">
<br>
<!-- <button name="add" id="add" class="btn btn-primary"
hidden="hidden">Add</button> -->
</div>
<div class="col-sm-2">
<input type="button" value="add" name="tableAdd" id="tableAdd"
class="btn btn-primary add add1">
</div>
</div>
<div class="col-xs-12">
<table id="tabledata" name="tabledata">
<thead>
<tr>
<th style="width: 50px; text-align: center !important;"
id="select">select</th>
<th style="width: 50px; text-align: center
!important;">Sl.No</th>
<th style="width: 125px; text-align: center
!important;">Date</th>
<th style="width: 175px; text-align: center
!important;">Service</th>
<th style="width: 80px; text-align: center
!important;">Charge</th>
<th style="width: 80px;">Amount</th>
<th style="width: 80px;">Unit</th>
<th style="width: 80px;">Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button type="button" id="delete-row" class="delete-row">Delete Row</button>
<button class="print" onclick="myFunction()">Print this page</button>
<br>
<label class="GrandTotalLabel" id="GrandTotalLabel">GRAND TOTAL</label>
<input type="text" name="txtGrandTotal" value="00.00" class="txtGrandTotal"
oninput="addTotal();" id="txtGrandTotal" readonly/>
</form>
This is My PHP code
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"]))
{
$numberOfRows = count($_POST['date']); // get the number of rows
for ($i = 0; $i < $numberOfRows; $i++) {
$date = $_POST["date"][$i];
$amount = $_POST["txtAmount"][$i];
$unit = $_POST["txtUnit"][$i];
$total = $_POST["txtTotal"][$i];
$sql = "INSERT INTO backup_master (backup_date, backup_amount,
backup_unit, backup_total) VALUES ('$date', '$amount', '$unit', '$total')";
$result = mysqli_query($conn, $sql);
}
}
?>
This is MY JAVASCRIPT CODE
<script type="text/javascript">
var lclCount=0;
$("#tableAdd").click(function(){
var sl_no = ($('#tabledata tr').length) - 1;
lclCount++;
sl_no++;
var date = $("#date").val();
var amount = $("#txtAmount").val();
var unit = $("#txtUnit").val();
var total = $("#txtTotal").val();
var markup = "<tr><td><input type='checkbox'
name='record' id='"+ lclCount +"'></td><td name='slno' class='slno' id
='slno-"+sl_no+"'>"
+ sl_no + "</td><td>"
+ date + "</td><td>"
+ amount + "</td><td>"
+ unit + "</td><td>"
+ parseFloat(total).toFixed(2) + "</td></tr>";
$("#tabledata").append(markup);
addTotal();
refreshAdd();
});
Here I want to save whatever is generated from dynamically created table data to the database. I tried a lot but unable to do so. Am getting an error saying undefined index date amount etc. Here I want to generate id for every automatically generated table row but unable to figure out how to do so.
Is there any other solution for this ?
Thank in Advance.
Okay....
In my code I'm created a div with class data in which I put four inputs date,amount,unit and total.
I add plus and minus buttons in last for add/remove row.
by clicking plus button clone of previous row appear in last
On submit data of all input will be send to the submit URL.
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"])){
$value = '';
for ($i=0;$i<count($_POST['date']);$i++) {
$value .= '("'.$_POST["date"][$i].'","'.$_POST["amount"][$i].'","'.$_POST["unit"][$i].'","'.$_POST["total"][$i].'"),';
}
$value = rtrim($value,",");
$sql = "INSERT INTO backup_master (backup_date, backup_amount, backup_unit, backup_total) VALUES ".$value;
$result = mysqli_query($conn, $sql);
}
echo '
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body><br />
<div class="container">
<h2>Vertical (basic) form</h2>
<form action="/action_page.php">
<div class="row data" divid="1">
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Date</span>
<input type="text" class="form-control date" value="'.date('Y/M/d').'" id="date-1" placeholder="Enter date" name="date[0]" />
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Amount</span>
<input type="text" class="form-control amount" data-id="1" value="0" id="amount-1" placeholder="Enter Amount" name="amount[0]" />
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Unit</span>
<input type="text" class="form-control unit" data-id="1" id="unit-1" value="0" placeholder="Enter Unit" name="unit[0]" />
</div>
</div>
<div class="col-md-2">
<div class="input-group">
<span class="input-group-addon">Total</span>
<input type="text" class="form-control total" id="total-1" readonly="readonly" name="total[0]" />
</div>
</div>
<div class="col-md-1">
<button class="btn btn-success btn-block plus" type="button" id="p-1">+</button>
<button class="btn btn-danger btn-block minus hide" type="button" id="m-1">-</button>
</div>
</div>
<div class="row"><div class="col-md-3"> </div></div>
<div class="row">
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Grand Total</span>
<input type="text" class="form-control" value="0" id="g-total" readonly="readonly" name="g_total" />
</div>
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-default" name="save">Submit</button>
</div>
</div>
</form>
</div>
</body>
</html>';
?>
<script type="text/javascript">
$(document).on('change','.unit,.amount',function(e) {
id = parseInt($(this).attr("id").replace("unit-", "").replace("amount-",""));
get_total(id);
});
function get_total(id){
unit_d = parseInt($('#unit-'+id).val());
amount = parseInt($('#amount-'+id).val());
total = Math.ceil(amount*unit_d);
$('#total-'+id).val(total);
var g_total = 0;
jQuery('.total').each(function(){
g_total = g_total+parseInt($(this).val());
});
$('#g-total').val(g_total);
}
/****************************JS for add new row****************************/
$(document).on('click','.plus',function(e) {
var thisRow = $('.data').last(".data");
var newid = parseInt(thisRow.attr('divid'))+1;
var cid = parseInt(thisRow.attr('divid'));
var date = $('#date-'+cid).val();
var amount = $('#amount-'+cid).val();
var n_unit = $('#unit-'+cid).val();
var total = $('#total-'+cid).val();
if(date=="") $('#date-'+cid).addClass('error'); else $('#date-'+cid).removeClass('error');
if(amount=="") $('#amount-'+cid).addClass('error'); else $('#amount-'+cid).removeClass('error');
if(n_unit=="") $('#unit-'+cid).addClass('error'); else $('#unit-'+cid).removeClass('error');
if(total=="") $('#total-'+cid).addClass('error'); else $('#total-'+cid).removeClass('error');
if((date!="")&&(amount!="")&&(n_unit!="")&&(total!="")){
$('#date-'+cid+',#amount-'+cid+',#unit-'+cid).attr('readonly','readonly');
newRow = thisRow.clone(true).insertAfter(thisRow).find('input').val('').end().
find('.date').each(function(){
$(this).attr('id', 'date-'+newid);
$(this).attr('name','date['+(newid-1)+']');
$(this).val($('#date-'+cid).val());
$(this).removeAttr('readonly');
}).end().find('.amount').each(function(){
$(this).attr('id', 'amount-'+newid);
$(this).attr('name','amount['+(newid-1)+']');
$(this).attr('data-id',newid);
$(this).val(0);
$(this).removeAttr('readonly');
}).end().find('.unit').each(function(){
$(this).attr('id', 'unit-'+newid);
$(this).attr('name','unit['+(newid-1)+']');
$(this).attr('data-id',newid);
$(this).val(0);
$(this).removeAttr('readonly');
}).end().find('.total').each(function(){
$(this).attr('id', 'total-'+newid);
$(this).attr('name','total['+(newid-1)+']');
$(this).val(0);
}).end().find('.plus').each(function(){
$(this).attr('id', 'p-'+newid);
$(this).attr('data-id', newid);
}).end().find('.minus').each(function(){
$(this).attr('id', 'm-'+newid);
}).end();
thisRow.next('.data').attr("divid",newid).addClass('child');
$('.minus').removeClass('hide');
$('.plus').addClass('hide');
$('#m-'+newid).addClass('hide');
$('#p-'+newid).removeClass('hide');
}
});
/****************************JS for add new row****************************/
/****************************JS for delete row****************************/
$('.minus').click(function(e) {
$(this).closest('.data').remove();
});
/****************************JS for delete row****************************/ </script>

Categories