Hi gladly I want to add a task row after I have clicked the save button. However what I have tried didn't seem to work unfortunately.
To show you the problem that I have. I will show you through a video where I have recorded myself. Here is the link: https://www.youtube.com/watch?v=d7L75HflxYo&feature=youtu.be
This is what I have tried:
var orderId=$('#id_order').val();
var $table = $('#taskTable');
$table.empty();
loadOrderTable(orderId);
And I have also tried this:
var orderId=$('#id_order').val();
var $table = $('#taskTable');
$table.empty();
//loadOrderTable(orderId);
$table.html(loadOrderTable(orderId));
Both attemps were placed in the body of the click function $('#saveOrder').click(function(e).
Now I will show you there rest of my code, in case if you need it.
$(function(){
$('#saveOrder').click(function(e){
e.preventDefault();
var form = $('#orderForm');
var allInput=form.serialize();
//var allInputJSON = JSON.stringify(allInput);
console.log('form serialize value: '+form.serialize());
//console.log('allInputJSON value: '+allInputJSON);
$.ajax( {
url: absUrl + "/user/orders/update/ordertasks",
data: {'allInput' : allInput},
success: function( response ) {
console.log('response value: '+ response );
//tried this after a user has added a task and that the gets filled with the new added row. But unfortunately it doesn't works.
var orderId=$('#id_order').val();
var $table = $('#taskTable');
$table.empty();
loadOrderTable(orderId);
}
} );
});
//addRowOnTaskTable(6);
var orderId=$('#id_order').val();
loadOrderTable(orderId);
//updateTotal();
//absUrl is declared in user/_layouts/template_head.blade.php
function loadOrderTable(order_id){
var order_id=order_id;
$.ajax({
url: absUrl+"/user/orders/load/tasks",
data: {'order_id' : order_id}
}).done(function(data) {
var data = $.parseJSON(data);
console.log('result loading table');
console.log(JSON.stringify(data));
$.each(data, function(index, value) {
$('#taskTable').append(
'<tr>'+
'<td>'
+value.task_name+
'</td>'+
'<td>'
+value.task_hour+
'</td>'+
'<td>'+ //pak load id ordertask ipv load hour voor je backend
'<input type="text" class="form-control hour" id="hour'+value.id+'" name="load_hour[]" value='+value.hour+' data-row='+value.id+' style="max-width:50%" placeholder="">'+
'</td>'+
'<td>'+
'<input type="text" class="form-control hour_salary" id="hour_salary'+value.id+'" name="load_hour_salaries[]" value='+value.hourprice+' data-row='+value.id+' style="max-width:50%" placeholder="">'+
'</td>'+
'<td>'+
'<input type="text" class="form-control" id="total_salary'+value.id+'" name="load_total_salaries[]" value='+value.totalprice+' readonly style="max-width:50%" placeholder="">'+
'</td>'+
'<td>'+
'<div class="dropdown">'+
'<button type="button" class="btn btn-danger dropdown-toggle selDelete" data-toggle="dropdown">'+
'<input id="check1" name="checkbox[]" type="checkbox" class="check" >'+
'<span class="caret-hover caret"></span>'+
'</button>'+
' <input type="hidden" name="load_id_task[]" value="'+value.id_task+'"/>'+
' <input type="hidden" name="load_id_ordertask[]" value="'+value.id+'"/>'+
'<ul class="dropdown-menu" aria-labelledby="selDelete" role="menu">'+
'<li><a class="deleteOrdertask" id="deleteOrdertask' + value.id + '" value="deleteOrdertask' + value.id + '" data-row='+value.id+' href= "#" data-method="delete" >Delete</a></li>'+
'</ul>'+
'</div>'
+'</td>'+
'</tr>');
});
$('.deleteOrdertask').click(function(e){
e.preventDefault();
var $this = $(this);
var rowId = $this.data('row');
deleteOtRow( rowId );
});
var deleteOtRow = function(rowId){
$deleteOrdertask = $("#deleteOrdertask" + rowId);
$($deleteOrdertask).parents('tr').remove();
var temp = $('#delete_ordertasks').val();
$('#delete_ordertasks').val(temp + rowId + ",");
//$(this).parents('tr').remove();
};
var updateTotal = function(rowId){
var rowId = rowId,
$hour_salary = $("#hour_salary" + rowId),
$total_salary = $("#total_salary" + rowId);
var hour = parseFloat($("#hour" + rowId).val()),
hour_salary = parseFloat($hour_salary.val());
if ( hour_salary.length > 0 )
$total_salary.val("0");
else
$total_salary.val( hour_salary * hour );
};
//updates elke totaal veld zonder dat een user een knop heeft ingedrukt.
$('.hour_salary').each(function() {
var $this = $(this);
updateTotal($this.data('row'));
});
$(".hour_salary").keyup(function() {
console.log('test keyup ');
var $this = $(this);
var rowId = $this.data('row');
$this.val( $this.val().replace(/\D/g,'') );
updateTotal( rowId );
});
$(".hour").keyup(function() {
var $this = $(this);
var rowId = $this.data('row');
$this.val( $this.val().replace(/\D/g,'') );
updateTotal( rowId );
});
});
}
function addRowOnTaskTable( id_task ){
var id_task=id_task;
console.log('addrow id '+ id_task);
$.ajax({
url: absUrl+"/user/orders/post/task",
data: {'id_task' : id_task}
}).done(function(data) {
var data = $.parseJSON(data);
console.log('add row JSON stringify'+JSON.stringify(data));
$('#taskTable').append(
'<tr>'+
'<td>'
+data.task_name+
'</td>'+
'<td>'
+data.task_hour+
'</td>'+
'<td>'+
'<input type="text" class="form-control hour" value="" data-row="'+data.id+'" name="hour[]" style="max-width:50%" placeholder="">'+
'</td>'+
'<td>'+
'<input type="text" class="form-control hour_salary" value="" data-row='+data.id+' name="hour_salary[]" style="max-width:50%" placeholder="">'+
'</td>'+
'<td>'+
'<input type="text" class="form-control" name="total_salary[]" value="" readonly style="max-width:50%" placeholder="">'+
'</td>'+
'<td>'+
'<div class="dropdown">'+
'<button type="button" class="btn btn-danger dropdown-toggle selDelete" data-toggle="dropdown">'+
'<input id="check1" name="checkbox[]" type="checkbox" class="check" >'+
'<span class="caret-hover caret"></span>'+
'</button>'+
' <input type="hidden" name="id_task[]" value="'+data.id+'"/>'+
' <input type="hidden" name="id_ordertask[]" value=""/>'+
' <input type="hidden" name="id_task[]" value="'+data.id+'"/>'+
'<ul class="dropdown-menu" aria-labelledby="selDelete" role="menu">'+
'<li><a class="deleteOrdertask' + data.id + '" href= "'+absUrl+"/user/orders/delete/ordertask"+'" data-method="delete" >Delete</a></li>'+
'</ul>'+
'</div>'
+'</td>'+
'</tr>');
$('.deleteOrdertask' + data.id ).click(function(e){
e.preventDefault();
$(this).parents('tr').remove();
});
var updateTotal = function(rowId){
var rowId = rowId,
$hour_salary = $("#hour_salary" + rowId),
$total_salary = $("#total_salary" + rowId);
var hour = parseFloat($("#hour" + rowId).val()),
hour_salary = parseFloat($hour_salary.val());
if ( hour_salary.length > 0 )
$total_salary.val("0");
else
console.log('tot ja '+ hour_salary * hour);
$total_salary.val( hour_salary * hour );
};
$(".hour_salary").keyup(function() {
console.log('test keyup ');
var $this = $(this);
var rowId = $this.data('row');
$this.val( $this.val().replace(/\D/g,'') );
updateTotal( rowId );
});
$(".hour").keyup(function() {
var $this = $(this);
var rowId = $this.data('row');
$this.val( $this.val().replace(/\D/g,'') );
updateTotal( rowId );
});
});
}
});
Related
I have a table and I append some rows if it is needed, when I add a row to my table the row number increase like 1, 2, 3, 4, and so on. but if I delete a row for example row number 4, it broke, and if add a new row it not start from number 4 it starts from number 5, how can I solve this problem.
this is my js code:-
$(document).ready(function () {
var rowcount, addBtn, tableBody;
addBtn = $('#addNew');
rowcount = $('#autocomplete_table tbody tr').length + 1;
tableBody = $('#autocomplete_table');
addBtn.click(function () {
$.ajax({
method: "get",
url: "book/getDepartment/" ,
success: function (data) {
console.log(data)
//rowcount=rowcount+1;
console.log(rowcount);
html = '<tr id="row_' + rowcount + '">';
html += '<td><button type="button" id="delete_' + rowcount + '" class=" btn btn-danger btn-sm remove delete_row"><i class="glyphicon glyphicon-remove-sign"></i></button></td>';
html += '<td><input type="text" data-field-name="book_name" name="book_name[]" id="book_name_' + rowcount + '" class=" form-control input-sm "></td>';
html += '<td><input type="text" data-field-name="edition" name="edition[]" id="edition_' + rowcount + '" class="form-control input-sm "></td>';
html += '<td><input type="text" required data-field-name="number" name="number[]" id="number_' + rowcount + '" class="form-control input-sm number"></td>';
html += '<td><input type="text" data-field-name="by_price" name="by_price[]" id="by_price_' + rowcount + '" class="form-control input-sm by_price"></td>';
html += '<td><input type="text" data-field-name="sell_price" name="sell_price[]" id="sell_price_' + rowcount + '" class="form-control input-sm sell_price"></td>';
html += '<td><input type="text" data-field-name="total_payment" name="total_payment[]" id="total_payment_' + rowcount + '" class="form-control input-sm total_payment"></td>';
html += '<td><select data-field-name="department" name="department[]" id="department_' + rowcount + '" class=" form-control input-sm department">';
html += '<option> انتخاب کنید...</option>';
$.each(data, function (i, item) {
html += '<option value="' + item.department_id + '">' + item.department_name + '</option>';
});
html += '</select></td>';
html += '</tr>';
rowcount++;
tableBody.append(html);
},
error: function () {
}
})
})
function delete_Row() {
var rowNo;
id = $(this).attr('id');
//console.log(id);
id_arr = id.split("_");
// console.log(id_arr);
rowNo = id_arr[id_arr.length - 1];
if (rowNo > 1) {
$('#row_' + rowNo).remove();
} else {
alert("شما نمی توانداین سطر را جذف کندید");
}
//console.log($(this).parent());
// $(this).parent().parent().remove();
}
function registerEvent() {
$(document).on('click', '.delete_row', delete_Row);
}
registerEvent();
});
success: function (data) {
rowcount = $('#autocomplete_table tbody tr').length + 1;
You have declare rowcount At Global scope that's why its value is equals to total row you add. when you delete any row you are not recounting total rows rowcount = $('#autocomplete_table tbody tr').length + 1; and it start with wrong number.just put your rowcount in side success function
I want to SUM the price of all dynamically created rows and display into total input field..I have tried some things but not working for me.I have posted my script and image that explains how it should works. Everything is working and saving in database just want total amount of all items. Please see image for clear concept. Total of 1st row is saving in total but not working for dynamically created rows.
Image:
It should work like this
Html:
<div class="form-group">
<label>Total</label>
<input readonly type="text" id="total_amount" class="form-control"
name="total_amount">
</div>
Script:
<script>
var counterr = 1;
$(document).ready(function () {
$('#unit_price,#item_quantity').change(function () {
// alert();
var unitPrice = $('#unit_price').val();
// console.log(unitPrice);
var quantity = $('#item_quantity').val();
// console.log(quantity);
var total = (unitPrice * quantity).toFixed(0);
$('#total_price').val(total);
$('#total_amount').val(total);
});
// Input Fields
var maxField = 100; //Input fields increment limitation
var addButton = $('#add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
$(addButton).click(function (e) {
e.preventDefault();
counterr++;
//Check maximum number of input fields
if (counterr < maxField) {
fieldHTML = makeNewRow(counterr);
$(wrapper).append(fieldHTML); //Add field html
// $('#department-'+counterr).select2();
// console.log("Unit price", counterr);
$('.unit_price' + counterr).change(function () {
// console.log("hello");
var unitPrice = $('.unit_price' + counterr).val();
// console.log(unitPrice);
var quantity = $('#item_quantity' + counterr).val();
// console.log(quantity);
var total = (unitPrice * quantity).toFixed(0);
$('#total_price' + counterr).val(total);
$('#total_price').each(function() {
subtotal += parseFloat($(this).val());
console.log('test',subtotal);
});
$('#total_amount').val(subtotal);
});
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('#newrow').remove(); //Remove field html
counterr = counterr--; //Decrement field counter
})
});
function makeNewRow(counterr) {
return '<div class="row" id="newrow">' +
'<div class="col-md-4">' +
'<div class="form-group">' +
'<select onChange="getPurchasePrice(this.value);" style="background-color: #f5f6f9" id="item_name' + counterr + '" class="form-control dep"' +
'placeholder="Enter Item" name="testing[]"' + '>' +
'<option value = "">Select Item</option>' + '>' +
'#foreach($items as $item)' + '>' +
'<option value = "{{$item->id}}">{{$item->item_name}}</option>' + '>' +
'#endforeach' + '>' +
'</select>' +
'</div>' +
'</div>' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<input style="background-color: #f5f6f9" type="number" id="item_quantity' + counterr + '" class="form-control"' +
'placeholder="Enter.." name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<input style="background-color: #f5f6f9" type="number" id="unit_price' + counterr + '" class="unit_price' + counterr + ' form-control"' +
'placeholder="Enter.." name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<div class="col-md-3">' +
'<div class="form-group">' +
'<input value="0" style="background-color: #f5f6f9" disabled type="text" id="total_price' + counterr + '" class="form-control"' +
'placeholder="Total" name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<a style="height:40px;margin-left:25px" href="javascript:void(0);" class="btn btn-danger remove_button">X</a>' +
'</div>'; //New input field html
}
/*function removeDiv(no){
$("#testingrow-"+no).remove();
x--;
}*/
</script>
Add a function to recalculate the grand total 'recalcGrandTotal'
var recalcGrandTotal = function() {
var grandTotal = 0; // Declare a var to hold the grand total
$("[id^=total_price]").each(function() { // Find all elements with an id that starts with 'total_price'
grandTotal += parseInt($(this).val()); // Add the value of the 'total_price*' field to the grand total
})
$('#total_amount').val(grandTotal); // append grand total amount to the total field
}
Then, hook this function up to the 'total price' recalculation function:
Find
$('#total_price' + counterr).val(total);
Add after:
recalcGrandTotal();
To substract from grand total upon removal of an item, hook this function up to the item removal function. Find:
counterr = counterr--; //Decrement field counter
Add after:
recalcGrandTotal();
I am trying to saved current updated row. My row contain select box and checkbox.If i change select box then selected value and checkbox status is updated.
function assignValue(itemsAll, itemLinked) {
var flage = true;
$.each(itemsAll, function (key, d) {
var tblRow = '<tr>';
tblRow += '<input id="hdnID" type="hidden" value="' + d.ItemCode + '" />';
tblRow += '<td style="width:20%"></span> ' + d.ItemCode + '</td>';
tblRow += '<td style="width:70%">' + d.ItemName + '</td>';
//alert("data"+d.Itme1);
if (itemPrice != null) {
var option = null;
for (var i = 0; i < itemPrice.d.length; i++) {
option += '<option value=' + itemPrice.d[i].ListNum + '>' + itemPrice.d[i].ListName + '</option>';
}
} else {
SessioExp(response.statusText);
}
tblRow += '<td style="width:20%"><div id="' + d.ItemCode + '"><select class="customSelect" name="dropdown">' + option + '</select></div></td>';
$.each(itemLinked, function (k, v) {
if (d.ItemCode == v.ITEMCODE) {
if (v.ISLINKED) {
tblRow += '<td style="width:10%" align="center"><span id="existingData" class="fa fa-times" aria-hidden="false" style="display: none;"></span></td>';
tblRow += '<td style="width:10%" align="center"><input type="checkbox" id="chkLinked" checked /></td>';
flage = false;
}
}
});
if (flage) {
tblRow += '<td style="width:10%" align="center"><span id="latestData" class="fa fa-check"></span></td>';
tblRow += '<td style="width:10%" align="center"><input type="checkbox" id="chkLinked"/></td>';
} else {
flage = true;
}
tblRow += '</tr>';
$("#tblStockTranslist tbody").append(tblRow);
});
}
Above code is set the row of table and my output is
Change id to class, as id must be unique in HTML like(for hidden field),
tblRow += '<input class="hdnID" type="hidden" value="' + d.ItemCode + '" />';
You can try onchange event like,
$('#tblStockTranslist').on('change','select,:checkbox',function(){
$tr = $(this).closest('tr');
code=$tr.find('.hdnID').val();
name=$tr.find('td:eq(1)').text();
value = !$(this).is(':checkbox') ? this.value : '';
// and so on...
console.log({code:code,name:name,value:value}); // make object like this
});
use this code
$("table").on("change","select",function()
{
var changed_row = $(this).parents("tr:eq(0)"),
selected_value = $(this).val();
});
after a long search i can't find a way to call an autocomplete function when the document is ready passing a specific variable.
So i got this function that works fine when i select element from autocomplete:
var option_row = <?php echo $option_row; ?>;
$('input[name=\'option\']').autocomplete({
'source': function(request, response) {
$.ajax({
url: 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(request),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
category: item['category'],
label: item['name'],
value: item['option_id'],
type: item['type'],
option_value: item['option_value']
}
}));
}
});
},
'select': function(item) {
html = '<div class="tab-pane" id="tab-option' + option_row + '">';
html += ' <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';
etc etc......
after many research i'm thinking to switch to another possible solution...
I wish to call this directly without select item but passing a variable to the function...
i'm trying doing this:
$(document).ready(function(e){
var option_row = <?php echo $option_row; ?>;
var req = 'item';
setOptions(req);
});
function setOptions(req){
$.ajax({
url: 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(req),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
category: item['category'],
label: item['name'],
value: item['option_id'],
type: item['type'],
option_value: item['option_value']
}
}));
}
});
'select': function(item) {
html = '<div class="tab-pane" id="tab-option' + option_row + '">';
html += ' <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';
etc, etc...
}
Now, i don't know what i should use instead of 'select': function(item) { to make it works.
Thanks in advance, any help is appreciated.
Well, i have finally make it... it was more simple than i thought
this is the code:
$(document).ready(function(e) {
var data = 'Adulti';
addOptions(data);
});
var option_row = <?php echo $option_row; ?>;
function addOptions(data){
var base_url = 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(data);
var n='';
$.ajax({
url: base_url,
dataType: 'json',
success: function(json) {
$.map(json, function(item) {
category = item['category'];
label = item['name'];
value = item['option_id'];
type = item['type'];
option_value = item['option_value'];
html = '<div class="tab-pane" id="tab-option' + option_row + '">';
html += ' <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['name'] + '" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][option_id]" value="' + item['value'] + '" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][type]" value="' + item['type'] + '" />';
etc, etc....
I have added Address,city and locality using jQuery in a dynamic added div element where the binding event is not working as expected:
I have below jQuery code:
<script type="text/javascript">
$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
if (counter > 19) {
alert("Only 20 Address allowed");
return false;
}
e.preventDefault();
var elems = '<div class="col-lg-5" id="Address' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group" id="city' + counter + '">' +
'<select name="city_name[]" id="city_name' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" id="removeButton' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';
//('#addressDiv').append(elems);
$('#addressDiv').append(elems);
$.ajax({
type: "Post",
url: "city_load.php",
success: function (html) {
$('#city_name' + counter).html(html);
}
});
$(document).on('change', '#city_name' + counter, function (ev) {
ev.preventDefault();
$city_id = $(this).val();
$.ajax({
type: "Post",
url: "ajax-dd3ck.php",
data: "city_id=" + $city_id,
cache: "false",
success: function (html) {
$('#locality_name' + counter).html(html);
}
});
});
//counter++;
return false;
});
$(document).on('click', '.removebtn', function () {
if (counter == 0)
{
alert("No more textbox to remove");
return false;
}
counter--;
$("#Address" + counter).remove();
$("#removeButton" + counter).remove();
});
});
</script>
My PHP Code for adding city in dropdown
city_load.php:
<?php
include("db.php");
$sql = "select * from city";
echo "<select name='city_name[]' id='city' class='city1'><option value='' selected ='selected'>Select City</option>";
$res = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($res)) {
echo "<option value='$row[city_id]'>$row[city_name]</option>";
}
echo "</select>";
?>
locality_load.php
<?php
include("db.php");
$city_id = $_POST['city_id'];
$sql = "select locality_id,locality_name,city_id from locality where city_id=$city_id";
$res = mysqli_query($con, $sql);
$result = mysqli_query($con, $sql) or die("query error");
while ($rows = mysqli_fetch_array($result)) {
$locality_id = $rows['locality_id'];
$locality_name = $rows['locality_name'];
echo "<option value=" . $locality_id . ">" . $locality_name . "</option>";
//echo '<option value="'.$locality_id.'">'.$locality_name.'</option>';
}
?>
The issue I am getting is that the first dynamic div is getting added and data is loading properly but for 2nd dynamic div it is not working.
Please have a look on screenshot:
save the counter value as a data-attr
eg
var elems = '<div class="col-lg-5 Address" data-id="' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group city" data-id="' + counter + '">' +
'<select name="city_name[]" data-id="' + counter + '" class="form-control city_name"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" data-id="' + counter + '" class="form-control locality_name"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" data-id="' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';
use a class for each element , bind events on class .
like
$(document).on('change','.city_name', function (ev) {
counter_id = $(this).attr('data-id');
}
so you will get the counter value and hope it will work for every div you created. (code not tested )
$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
if (counter > 19) {
alert("Only 20 Address allowed");
return false;
}
e.preventDefault();
var $elems = $('<div class="col-lg-5" id="Address' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group" id="city' + counter + '">' +
'<select name="city_name[]" id="city_name' + counter + '" data-index="' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" id="removeButton' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>');
//('#addressDiv').append(elems);
$('#addressDiv').append($elems);
$.ajax({
type: "Post",
url: "city_load.php",
success: function (html) {
$elelms.find('select').html(html);
}
});
counter++;
return false;
});
$(document).on('change', 'select', function (ev) {
var cc = $(this).attr('data-index');
ev.preventDefault();
$city_id = $(this).val();
$.ajax({
type: "Post",
url: "ajax-dd3ck.php",
data: "city_id=" + $city_id,
cache: "false",
success: function (html) {
$('#locality_name' + cc).html(html);
}
});
});
$(document).on('click', '.removebtn', function () {
if (counter == 0)
{
alert("No more textbox to remove");
return false;
}
counter--;
$("#Address" + counter).remove();
$("#removeButton" + counter).remove();
});
});
There are maybe some problem!