append line add autocomplete jQuery - javascript

I have made an autocomplete on a form where its possible to add new line.
However my autocomplete locks only to the first item.
Can you help me getting the autocomplete to work on appended lines.
jsFiddle: https://jsfiddle.net/r65x9aj0/3/
Javascript:
var globalNewIndex = 0;
var availableAttributes = [
"account_address",
"account_address_city",
"account_address_country",
"account_address_state",
"account_address_street1",
"account_address_street2",
"account_address_zip",
"account_email",
"account_login",
"account_name",
"account_number",
"account_telephone"
];
$(document).ready(function() {
$('#fixed_name_'+globalNewIndex).autocomplete({
source: availableAttributes
});
$("#add").click(function() {
var newIndex = globalNewIndex+1;
var changeIds = function(i, val) {
return val.replace(globalNewIndex,newIndex);
}
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
globalNewIndex++;
$('#fixed_name_'+globalNewIndex).autocomplete({
source: availableAttributes
});
$('#mytable tbody>tr:last .emptythis').val('');
$("#mytable tbody>tr:last").each(function() {this.reset();});
return false;
});
});
HTML:
<table id="mytable" class="table table-hover">
<thead>
<tr style="font-weight: bold">
<td>Item number
</td>
<td>Price EUR
</td>
</tr>
</thead>
<tbody>
<tr class="person">
<td>
<input type="text" name="fixed_name[0]" id="fixed_name_0" class="form-control emptythis" autocomplete="off" />
</td>
<td>
<input type="number" name="fixed_price[0]" id="fixed_price_0" class="form-control emptythis" autocomplete="off" />
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-md-3">
<button type="button" class="btn btn-success btn-block btn-lg" id="add">Add line
</button>
</div>
<div class="col-md-9">
<button type="submit" class="btn btn-primary btn-block btn-lg" id="searchinternal">Update
</button>
</div>
</div>
</form>

Here is an updated jsfiddle following your code:
Updated fiddle
I initialized Autocomplete dynamically and created a template for the new row because the clone function cloned the instance of autcomplete, which is not good.
Here is your new javascript:
$(document).ready(function() {
$(document).on('keydown.autocomplete', '#mytable tbody>tr:last input', function() {
$(this).autocomplete({
source: availableAttributes
});
});
$("#add").click(function() {
var newIndex = globalNewIndex+1;
var changeIds = function(i, val) {
return val.replace(globalNewIndex,newIndex);
}
var $newRow = $('<tr class="person"><td><input type="text" class="form-control emptythis ui-autocomplete-input" autocomplete="off"></td><td><input type="number" name="fixed_price[1]" id="fixed_price_1" class="form-control emptythis" autocomplete="off"></td></tr>');
$newRow.insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds);
globalNewIndex++;
$('#mytable tbody>tr:last .emptythis').val('');
$("#mytable tbody>tr:last").each(function() {this.reset();});
return false;
});
});

// previous code
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
// changed lines of code
var $newRow = $('<tr>' + $('#mytable tbody>tr:first').html() + '</tr>');
$newRow.find('input').attr('name', changeIds ).attr('id', changeIds );
$('#mytable tbody').append($newRow);
The code didn't work because of the clone(true).
I would suggest a 'template' function for the row though.
As for the previous comment, I would not suggest putting it .on('keypress', ... because this gets fired every time you press a key (you can however listen only 'once' with one, but this won't solve your issue, since it won't get fired the 'second' time then).

It is not working because of you are adding the textbox dynamically and for dynamic html the autocomplete is instantiate in different way like:
var selector = '.searchInput';
$(document).on('keydown.autocomplete', selector, function() {
$(this).autocomplete(options);
});

Related

How to delete dynamically added row using jQuery?

I am trying to put a 'Delete' button after each of the row of my table.The delete button should function in such a way that it should only get activated when a new row is added. And if out of two rows one row is deleted the delete button of the existing row should also get deactivated.Any help will be appreciated. Thanks.
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
$(document).on('click','.Buttons', function(e) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('select:last').val()){
alert("Please fill all the fields in the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = match[1] + (cindex);
}
}
});
$tr.after($clone);
});
/*`For delete button*/
$(document).on("click", '.DeleteButton', function() {
$(this).closest("tr").remove();
});
/*for enable field*/
$(document).on("click", '.DeleteButton', function() {
$(this).closest("tr").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="16%"></td>
</tr>
</thead>
<tbody>
<tr id="id01" name="row">
<td>
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField()" >
<option value="">Select</option>
<option value="GDS">Guides</option>
<option value="LOF">Latest Offers</option>
<option value="TEM">Templates</option>
<option value="VID">Videos</option>
</select>
</td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" id="Button4" value="Delete Row" disabled="true" class="DeleteButton" name="Button4" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
You can get the count of rows in the table on every 'Add New Row' button and 'Delete Row' button click by:
var Count = $('#dataTable tr').length;
Then using the value of Count you can enable/disable the delete button e.g
if(Count < 2 )
//code to disable
else
//code to enable
I don't know if I get your question right, but I would try to do it like so:
I would handle this over a class namend 'active'. You also can give this class a disabled style. Also I would toggle the show/hide function of jquery if the button was clicked. And if one button is the last man standing - I would hide all. So it cant be clicked anymore. You can also ignore the 'active'-Class if you juste need to show/hide the buttons. The buttons should have a specific class 'del-btn'.
Note: Class 'active' is just for showing the button but disable/enable. Show/hide is for 'removing' the button.
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
$(document).on('click','.Buttons', function(e) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('select:last').val()){
alert("Please fill all the fields in the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = match[1] + (cindex);
}
}
});
// If you want to activate ALL buttons:
$('.del-btn').addClass('active');
// If just the added row should be active:
$clone.find('.del-btn').addClass('active');
$(".del-btn").show();
$tr.after($clone);
});
/*`For delete button*/
$(document).on("click", '.DeleteButton', function() {
if(!$(this).hasClass('active')){
// removing is allowed
$(this).closest("tr").remove();
// Now you can check, if the rest should be shown or not
var btns = $('.del-btn').length; // count the buttons in the dom
if(btns>0){
if(btns == 1){
$(".del-btn").hide();
}else{
$(".del-btn").show();
}
}
}else{
// removing is disallowed
}
});
``````````````````````````for enable field``````````````````````
$(document).on("click", '.DeleteButton', function() {
$(this).closest("tr").remove();
});

HTML jquery: onclick function to delete dynamic table row is not calling

I just want to delete dynamically created row, but iam unable to call the function using jquery and javascript.
const dynamic_JS = ({ sno, optionVal, price }) => `<tr><td>${sno}</td> <td><select name="selectProduct" class="form-control" selected="${optionVal}"><option value="0"> -- Select One --</option><option value="1"> IPhone </option><option value="2"> MAC </option><option value="3"> Windows </option></select></td> <td><input type="text" class="form-control" value="${price}" title="" ></td> <td><button type="button" class="remove-row btn btn-info glyphicon glyphicon-remove" ></button></td> </tr>`;
// onclick=\'removeRow(this)\'
//window.onload=function(){}
$(document).ready(function() {
var template_add = $('#hidden-template').text();
function render(props) {
return function(tok, i) {
return (i % 2) ? props[tok] : tok;
};
}
var items = [ { sno: '1', optionVal: '0', price: '0' } ];
var dynamic_HTML = template_add.split(/\$\{(.+?)\}/g);
$('tbody').append(items.map(function(item) {
return dynamic_HTML.map(render(item)).join('');
}));
});
// https://stackoverflow.com/a/35592412/5081877
$('#number_only').on('input propertychange', function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
$('.add-new').on('click', function () {
$("#productTable").each(function () {
var tr_last = $('tbody > tr:last', this).clone();
var td_no = tr_last.find('td:first');
var serialNumber = parseInt(td_no.text()) + 1;
// https://stackoverflow.com/a/6588327/5081877
var tr_first_input = $('tbody > tr:first > td:nth-child(3) > input');
var tr_first_price = parseFloat(tr_first_input.val()) || 0;
console.dir( tr_first_price );
totalamount += tr_first_price;
$('#totalAdd').text(totalamount);
var tr_first_selected = $('tbody > tr:first > td:nth-child(2) > select option').filter(":selected");
// option:selected | .find(":selected") ~ .text(), ~.attr('value');
var selectedValue = tr_first_selected.val(), optionText = tr_first_selected.text().trim();
console.log(' Text : ', optionText );
console.log('Value : ', selectedValue );
// https://stackoverflow.com/a/39065147/5081877
$('tbody', this).append([
{ sno: serialNumber, optionVal: selectedValue, price: tr_first_price }
].map(dynamic_JS).join(''));
var last_optionSel = $('tbody#mainBody > tr:last > td:nth-child(2) > select');
last_optionSel.val( selectedValue );
tr_first_input.val( 0 );
// https://stackoverflow.com/a/13089959/5081877
var first_optionSel = $('#productOption');
//$('tbody > tr:first > td:nth-child(2) > select ');
first_optionSel.val( 0 );
return;
});
});
var totalamount = 0; // tr#mainRow
$('table#productTable > tbody ').on('keyup', 'input', function(e) {
var total =
$(e.delegateTarget)
.find('input')
.map(function() {
return parseFloat($(this).val()) || 0;
})
.get()
.reduce(function(a, b) {
return a + b;
});
$('#total').text(total);
});
<!-- Remove row - javascript & Jquery -->
$('.remove-row').on('click', function () {
$("#productTable").each(function () {
// added total minus deleting element price.
$(this).closest('tr').remove();
});
});
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>
<table id="productTable" class="table table-hover table-bordered">
<thead>
<tr>
<th>No.</th><th>Product</th><th>Price</th><th>Action</th>
</tr>
</thead>
<tbody id="mainBody">
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td>
Expected Total:<span id="total">0</span><br>
Added Total:<span id="totalAdd">0</span>
</td>
<td></td>
</tr>
</tfoot>
</table>
<button type="button" class="add-new btn btn-info" id="add-new">Add New Income</button>
<script id="hidden-template" type="text/x-custom-template">
<tr id="mainRow">
<td>${sno}</td>
<td>
<select name="selectProduct" id="productOption" class="form-control" selected="${optionVal}">
<option value="0"> -- Select One --</option>
<option value="1"> IPhone </option>
<option value="2"> MAC </option>
<option value="3"> Windows </option>
</select>
</td>
<td>
<input id="number_only" pattern="[0-9]" type="text" class="form-control" />
</td>
<td><!-- glyphicon-plus | glyphicon-remove -->
<button type="button" class="add-new btn btn-info glyphicon glyphicon-plus"></button>
</td>
</tr>
</script>
</body>
Stackoverflow snippet - using javascript onclick function remove current row is working fine.
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
as part of jsfiddle - test and plane html file the code is not working at-least with javascript.
Unable to delete|call delete row function. while deleting row remove the price from the Added Total.
I should only allow number for the input tag, but it is working only for the first row input element. Input type must be text only. type number allows these like {.+-}
Iam unable to solve it as new to jquery and its xpath element navigation.
There are two issues with your code:
$('table#productTable:.remove-row').on('click', function () {
here :. is an syntax error, and it is showing in console.
Second to put an event listener on dynamic html, you have to use $(document).on() like:
$(document).on('click', '.remove-row', function(){
Check the updated working fiddle
here
I have added events using on click event handler as elements get added dynamically.
Have updated both events:
1. Event for remove button
$('table#productTable').on('click', '.remove-row', function() {
//$("#productTable").each(function () {
// added total minus deleting element price.
$(this).closest('tr').remove(); // https://stackoverflow.com/a/11553788/5081877
//$(element).parent().remove();
//});
});
2. Event for input tag
$('table#productTable').on('input propertychange',' > tbody > tr > td:nth-child(3) > input', function() {
$.each($('input[type=text]'), function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
});
Refer this fiddle
Please change $('.row).onclick like this
$('table#productTable').on('click', '.remove-row', function()
And remove this $("#productTable").each(function () {

Duplicating table rows with clone

I am having an issue I am struggling to resolve. I have two tables
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin alignment" id="table1">
<thead>
<tr>
<th>Campaign Type</th>
<th>Deployment Date</th>
<th>Additional Information</th>
</tr>
</thead>
<tbody>
<tr class='template'>
<td>
<select class="selectType" name='typeInput[0][campType]' id="campInput">
<option value=""></option>
<option value="Main">Main</option>
<option value="Other">Standalone</option>
</select>
</td>
<td>
<input type="text" name='typeInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>
</td>
<td>
<textarea name='typeInput[0][addInfo]' id="additionalInput" placeholder='Additional Information' class="form-control noresize"></textarea>
</td>
</tr>
</tbody>
</table>
<a id='add' class="pull-right btn btn-default">Add Row</a>
<a id='delete' class="pull-right btn btn-default">Delete Row</a>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin alignment" id="table4">
<thead>
<tr>
<th>Additional Information</th>
<th>Deployment Date</th>
</tr>
</thead>
<tbody>
<tr class='template4'>
<td>
<textarea name='amendsInput[0][addInfo]' id="additionalInput" placeholder='Additional Information' class="form-control noresize"></textarea>
</td>
<td>
<input type="text" name='amendsInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>
</td>
</tr>
</tbody>
</table>
<a id='add4' class="pull-right btn btn-default">Add Row</a>
<a id='delete4' class="pull-right btn btn-default">Delete Row</a>
</div>
</div>
</div>
</div>
One table has 3 inputs, the other has 2. When the add button is pushed on either table, I am cloning the table row, which includes cloning a datepicker.
Things have been going fine but now I have a problem. The second table I end everything with 4 e.g. table4, template4, add4 and delete4. I then duplicated the Javascript from the preious table but added 4 to everything (I duplicated it because this table has different inputs). This resulted in the following code.
$(function() {
initJQueryPlugins();
$('#add').on('click', function() {
$last_row = $('#table1 > tbody > tr').last();
if(!hasValues($last_row)){
alert('You need to insert at least one value in last row before adding');
} else {
add_row($('#table1'));
}
});
$('#delete').on('click', function() { delete_row($('#table1')); });
$('#add4').on('click', function() {
$last_row = $('#table4 > tbody > tr').last();
if(!hasValues4($last_row)){
alert('You need to insert at least one value in last row before adding');
} else {
add_row4($('#table4'));
}
});
$('#delete4').on('click', function() { delete_row4($('#table4')); });
});
function add_row($table) {
var tr_id = $table.find('tr').length - 1;
var $template = $table.find('tr.template');
var $tr = $template.clone().removeClass('template').prop('id', tr_id);
$tr.find(':input').each(function() {
if($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker').removeData('datepicker');
}
var input_id = $(this).prop('id');
input_id = input_id + tr_id;
$(this).prop('id', input_id);
var new_name = $(this).prop('name');
new_name = new_name.replace('[0]', '['+ tr_id +']');
$(this).prop('name', new_name);
$(this).prop('value', '');
});
$table.find('tbody').append($tr);
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
$(".selectType", $tr).select2({
tags: true
});
}
function hasValues($row){
$optVal = $row.find('td option:selected').text();
$inputVal = $row.find('td input').val();
$textVal = $row.find('td textarea').val();
if($optVal != "" || $inputVal != "" || $textVal != ""){
return true;
} else {
return false;
}
}
function delete_row($table) {
var curRowIdx = $table.find('tr').length - 1;
if (curRowIdx > 2) {
$("#" + (curRowIdx - 1)).remove();
curRowIdx--;
}
}
function add_row4($table4) {
var tr_id = $table4.find('tr').length - 1;
var $template = $table4.find('tr.template4');
var $tr = $template.clone().removeClass('template4').prop('id', tr_id);
$tr.find(':input').each(function() {
if($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker').removeData('datepicker');
}
var input_id = $(this).prop('id');
input_id = input_id + tr_id;
$(this).prop('id', input_id);
var new_name = $(this).prop('name');
new_name = new_name.replace('[0]', '['+ tr_id +']');
$(this).prop('name', new_name);
$(this).prop('value', '');
});
$table4.find('tbody').append($tr);
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
}
function hasValues4($row4){
$inputVal = $row4.find('td input').val();
$textVal = $row4.find('td textarea').val();
if($inputVal != "" || $textVal != ""){
return true;
} else {
return false;
}
}
function delete_row4($table4) {
var curRowIdx = $table4.find('tr').length - 1;
if (curRowIdx > 2) {
$("#" + (curRowIdx - 1)).remove();
curRowIdx--;
}
}
function initJQueryPlugins() {
add_row($('#table1'));
add_row4($('#table4'));
}
I have set up a working FIDDLE
The problem is this. If you start adding a few rows in the first table, this all works fine. After this, add a few rows in the second table. This seems to work fine. However, now start deleting rows in the second table. For some reason it seems to also delete rows in the first table.
So my main question is why does this happen? Additionally, is there any way I can do this without duplicating the code? The second table does not use select2.
Thanks
You are deleting this:
$("#" + (curRowIdx - 1)).remove();
This id is also available in the first table, you have to choose a more specified selector
like:
$table4.find("#" + (curRowIdx - 1)).remove();
or better: (comment from K. Bastian above)
$table4.find('tr').last().remove()
I edited your sample here:
https://jsfiddle.net/cLssk6bv/
Here I also deleted the dublicated code, only the different insert method still exist:
https://jsfiddle.net/cLssk6bv/1/

Issue with genenerating form fields dynamically

I am using the below script in my python application for generating rows of form fields by clicking an “add row” button. But I am able to do this only if there is at-least one blank row, can I get some help in getting the below script changed so that new row can be added without any blank rows. Also I need to have a timepicker field in the same row
$(function() {
$("div[data-toggle=fieldset]").each(function() {
var $this = $(this);
//alert($this)
//Add new entry
$this.find("button[data-toggle=fieldset-add-row]").click(function() {
var target = $($(this).data("target"))
console.log(target);
var oldrow = target.find("tr[data-toggle=fieldset-entry]:last");
var row = oldrow.clone(true, true);
console.log(row.find(":input")[0]);
var elem_id = row.find(":input")[0].id;
var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1;
row.attr('data-id', elem_num);
row.find(":input").each(function() {
console.log(this);
var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + (elem_num) + '-');
$(this).attr('name', id).attr('id', id).val('').removeAttr("checked");
});
oldrow.after(row);
}); //End add new entry
//Remove row
$this.find("button[data-toggle=fieldset-remove-row]").click(function() {
if($this.find("tr[data-toggle=fieldset-entry]").length > -1) {
var thisRow = $(this).closest("tr[data-toggle=fieldset-entry]");
thisRow.remove();
}
});
//End remove row
});
});
HTML used as below
<div class="form-group">
<div data-toggle="fieldset" id="dimdetail-fieldset">
<div class="col-sm-5">
<button type="button" class="btn btn-primary pull-left" data-toggle="fieldset-add-row" data-target="#dimdetail-fieldset" id="add_time"> + Time</button>
</div>
<br>
<br>
<br>
<div class="col-md-12">
<div class ="table-responsive">
<table id="table_id" class="table table-bordered">
<tr>
<th>Total Hours</th>
<th>Inspector</th>
<th>Inspection</th>
<th>Remarks</th>
<th></th>
</tr>
<tr data-toggle="fieldset-entry">
<td><input class="form-control" id="timesheet_time_details-0-total_hours" name="timesheet_time_details-0-total_hours" size="12" type="text" value="">
</td>
<td><input class="form-control" id="timesheet_time_details-0-inspector" name="timesheet_time_details-0-inspector" size="12" type="text" value="">
</td>
<td><select class="form-control" id="timesheet_time_details-0-testmethod" name="timesheet_time_details-0-testmethod"><option value="1">Test Method</option><option value="2">UT Test</option></select>
</td>
<td><textarea class="form-control" id="timesheet_time_details-0-remarks" name="timesheet_time_details-0-remarks" rows="3"></textarea>
</td>
<td><button type="button" data-toggle="fieldset-remove-row" id="dimdetail-0-remove">-</button></td>
</tr>
</table>
</div>
</div>
</div>
</div>
thanks ,
prasobhraj
$(function() {
// $("div[data-toggle=fieldset]").each(function() {
var $this = $(this);
//alert($this)
//Add new entry
$this.find("button[data-toggle=fieldset-add-row]").click(function() {
var target = $($(this).data("target"))
console.log(target);
var oldrow = target.find("tr[data-toggle=fieldset-entry]:last");
var row = oldrow.clone(true, true);
console.log(row.find(":input")[0]);
var elem_id = row.find(":input")[0].id;
var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1;
row.attr('data-id', elem_num);
row.find(":input").each(function() {
console.log(this);
var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + (elem_num) + '-');
$(this).attr('name', id).attr('id', id).val('').removeAttr("checked");
});
oldrow.after(row);
}); //End add new entry
//Remove row
$this.find("button[data-toggle=fieldset-remove-row]").on('click',function() {
if($this.find("tr[data-toggle=fieldset-entry]").length > -1) {
var thisRow = $(this).closest("tr[data-toggle=fieldset-entry]");
thisRow.remove();
}
});
});
try this its working..

Filling and creating table with input value

My inputs:
<input id="id_name" name="name"/>
<input id="id_age" name="age"/>
<button id="add_btn"></button>
After every click on button add_btn I need append my table(<tr>) with form input value. At the start, the table is empty. Only <tbody>.
<table class="mytab">
<tbody>
<tr>
<td> HERE_VALUE_FROM_NAME_FIELD</td>
<td>HERE_VALUE_FROM_AGE_FIELD</td>
</tr>
<tr>
<td> HERE_NEXT_VALUE_FROM_NAME_FIELD</td>
<td>HERE_NEXT_VALUE_FROM_AGE_FIELD</td>
</tr>
</tbody>
</table>
Onclick function:
$("#myform").on('click', "#add_btn", function(e) {
e.preventDefault();
//fill table
});
Try like this:
HTML
<input id="id_name" name="name"/>
<input id="id_age" name="age"/>
<button id="add_btn">click</button>
<table border="1" class="mytab"></table>
JQuery:
$("#add_btn").on('click', function(e) {
e.preventDefault();
var name = $('#id_name').val(),
age = $('#id_age').val();
$('<tr><td>'+name+'</td><td>'+age+'</td></tr>').appendTo( $('.mytab') );
});
DEMO
http://jsfiddle.net/jogesh_pi/dfg2R/
Helpful link:
appendTo()
A little search about jQuery DOM will give you the answer. see jQuery.append()
$( '#table_id' ).append(
$('<tr />').append(
$('<td/>').text($('#id_name').value())
).append(
$('<td/>').text($('#id_age').value())
)
);
You can use the insertRow and insertCell on the returned row.
http://jsfiddle.net/dfg2R/2/
insertCell
insertRow
Here is an example:
$("#myform").on('click', "#add_btn", function(e) {
e.preventDefault();
var table = $("table.mytab")[0]
var newRow = table.insertRow(0);
var newCell = newRow.insertCell();
newCell.innerText = $("#id_name").val();
var newCell = newRow.insertCell();
newCell.innerText = $("#id_age").val();
});
If you want to use jQuery you could use .append()
$(".myTab tbody").append("<tr><td>" + valueName+ "</td><td> + valueAge + </td></tr>");

Categories