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/
Related
I have implemented a checkall checkbox for the table but the table has pagination and DOM only gets the elements currently showing on the page. my implementation is not working on other paginations. how can we achieve this task?
.cshtml code
<table id="instruments" class="table table-bordered table-striped table-condensed table-hover smart-form has-tickbox" style="width: 100%;">
<thead>
<tr>
<th>
<input id="chkAffectCheckboxGroup" type="checkbox" />
</th>
<th data-class="expand" style="white-space: nowrap">#Model.idResource</th>
<th data-hide="phone" style="white-space: nowrap">#Model.SResource</th>
<th data-hide="phone" style="white-space: nowrap">#Model.LocationResource</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Instruments.Count; i++)
{
var values = Model.Instruments[i].Value.Split('~');
var status = values.Length > 0 ? values[0] : "";
var location = values.Length > 1 ? values[1] : "";
<tr>
<td>
<label class="checkbox">
#Html.CheckBoxFor(m => m.Instruments[i].Selected, new { #class = "chkInst" })
<i></i>
</label>
</td>
<td><label>#Model.Instruments[i].Text</label></td>
<td><label>#status</label></td>
<td><label>#location</label></td>
</tr>
}
</tbody>
</table>
Jquery Code
$(document).ready(
console.log("jquery called"),
manageCheckboxGroup('chkAffectCheckboxGroup', 'chkInst')
);
JavaScript Code
function manageCheckboxGroup(masterCheckboxId, slaveCheckboxesClass) {
$("#" + masterCheckboxId).click(function () {
$("." + slaveCheckboxesClass).prop('checked', this.checked);
});
$("." + slaveCheckboxesClass).click(function () {
if (!this.checked) {
$("#" + masterCheckboxId).prop('checked', false);
}
else if ($("." + slaveCheckboxesClass).length == $("." + slaveCheckboxesClass + ":checked").length) {
$("#" + masterCheckboxId).prop('checked', true);
}
});
}
I've a form on my website where I'm getting multiple event details from my customers. They can share event details and event date.
I want to let them able to add multiple events with details but dynamically. Currently I wrote JavaScript for this and it's working fine.
Now, what I want is each time the value for next date should be grater than the previous one. So If they added 2 events suppose, the date for the second event should be based on date for first event and should be greater and same is true for upcoming dates.
How can I do that?
var tableCount = 1;
var index = 1;
$(document).on('click', 'button.add_time', function(e) {
e.preventDefault();
tableCount++;
$('#timeTable').clone().attr('id', "timeTable" + tableCount).appendTo('#table');
$('#timeTable' + tableCount).find("input").val("");
index++;
$('#timeTable' + tableCount + ' .aa').html(tableCount);
});
$(document).on('click', 'button.removeTime', function() {
var closestTable = $(this).closest('table');
if (closestTable.attr('id') != "timeTable") {
closestTable.remove();
}
tableCount--;
if (tableCount < 1) {
tableCount = 1;
}
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table" class="form-group">
<table id="timeTable" class="tg">
<tr class="form-group">
<td class="aa">1</td>
<td class="tg-yw4">
<button class="btn form-control btn-danger removeTime">Remove Events</button>
</td>
<td class="col-sm-4">
<input placeholder="Event Date" name="events[]" class="input-lg" type="text" onfocus="(this.type='date')">
</td>
</tr>
<tr>
<td class="aa">1</td>
<td class="tg-yw4">Event Description:</td>
<td>
<input name="event_descriptions[]" type="text" placeholder="Event description:" />
</td>
</tr>
</table>
</div>
<div class="my-5">
<button class="add_time btn btn-info">Add More Events</button>
</div>
Whenever user inputs the date in input box you can check if the date which he/she has enter is less then previous date by looping through all previous dates inputs using each loop and depending on this show some error message.
Demo Code :
var tableCount = 1;
var index = 1;
//on input of date
$(document).on('input', 'input[name*=events]', function(e) {
//get that date
var edate = new Date($(this).val());
var $this = $(this).siblings("span.error");
$this.text("")//empty previous error if any
//loop through dates inputs
$("input[name*=events]").each(function() {
if ($(this).val() != null) {
//get input value
var sdate = new Date($(this).val())
//check user input is less then previous date
if (edate < sdate) {
console.log("date is less then previous date");
$this.text("date is less then previous date")//show eror
}
}
})
});
$(document).on('click', 'button.add_time', function(e) {
e.preventDefault();
tableCount++;
$('#timeTable').clone().attr('id', "timeTable" + tableCount).appendTo('#table');
$('#timeTable' + tableCount).find("input").val("");
index++;
$('#timeTable' + tableCount + ' .aa').html(tableCount);
});
$(document).on('click', 'button.removeTime', function() {
var closestTable = $(this).closest('table');
if (closestTable.attr('id') != "timeTable") {
closestTable.remove();
}
tableCount--;
if (tableCount < 1) {
tableCount = 1;
}
return false;
});
.error {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table" class="form-group">
<table id="timeTable" class="tg">
<tr class="form-group">
<td class="aa">1</td>
<td class="tg-yw4">
<button class="btn form-control btn-danger removeTime">Remove Events</button>
</td>
<td class="col-sm-4">
<!--added this to show error -->
<span class="error"></span>
<input placeholder="Event Date" name="events[]" class="input-lg" type="text" onfocus="(this.type='date')">
</td>
</tr>
<tr>
<td class="aa">1</td>
<td class="tg-yw4">Event Description:</td>
<td>
<input name="event_descriptions[]" type="text" placeholder="Event description:" />
</td>
</tr>
</table>
</div>
<div class="my-5">
<button class="add_time btn btn-info">Add More Events</button>
</div>
I am having trouble pulling information from dynamically created text fields within a container from bootstrap. For what I have for "Dropoff Locations", I need to be able to store the information of an address into one address, and then each full address into an array of addresses. I am unsure of how to do this, especially using jQuery.
<!-- Dropoff Locations -->
<div class=" mb-4">
<div class="card border-0 shadow">
<div class="card-body text-center">
<h5 class="card-title mb-0">Drop-Off Location(s)</h5>
<hr>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 table-responsive">
<table class="table table-bordered table-hover table-sortable" id="tab_logic">
<thead>
<tr>
<th class="text-center">
Street Address
</th>
<th class="text-center">
City
</th>
<th class="text-center">
State
</th>
</tr>
</thead>
<tbody>
<tr id='addr0' data-id="0" class="hidden">
<td data-name="name">
<input type="text" name='name0' placeholder='Street Address' class="form-control"/>
</td>
<td data-name="mail">
<input type="text" name='mail0' placeholder='City' class="form-control"/>
</td>
<td data-name="desc">
<input type="text" name="desc0" placeholder="State" class="form-control"/>
</td>
<td data-name="del">
<button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove'><span aria-hidden="true">×</span></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<a id="add_row" class="btn btn-primary float-right text-white">Add Stop</a>
This is the script code
$(document).ready(function() {
$("#add_row").on("click", function() {
// Dynamic Rows Code
// Get max row id and set new id
var newid = 0;
$.each($("#tab_logic tr"), function() {
if (parseInt($(this).data("id")) > newid) {
newid = parseInt($(this).data("id"));
}
});
newid++;
var tr = $("<tr></tr>", {
id: "addr"+newid,
"data-id": newid
});
// loop through each td and create new elements with name of newid
$.each($("#tab_logic tbody tr:nth(0) td"), function() {
var td;
var cur_td = $(this);
var children = cur_td.children();
// add new td and element if it has a nane
if ($(this).data("name") !== undefined) {
td = $("<td></td>", {
"data-name": $(cur_td).data("name")
});
var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
c.attr("name", $(cur_td).data("name") + newid);
c.appendTo($(td));
td.appendTo($(tr));
} else {
td = $("<td></td>", {
'text': $('#tab_logic tr').length
}).appendTo($(tr));
}
});
// add delete button and td
/*
$("<td></td>").append(
$("<button class='btn btn-danger glyphicon glyphicon-remove row-remove'></button>")
.click(function() {
$(this).closest("tr").remove();
})
).appendTo($(tr));
*/
// add the new row
$(tr).appendTo($('#tab_logic'));
$(tr).find("td button.row-remove").on("click", function() {
$(this).closest("tr").remove();
});
// Sortable Code
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
};
$(".table-sortable tbody").sortable({
helper: fixHelperModified
}).disableSelection();
$(".table-sortable thead").disableSelection();
$("#add_row").trigger("click");
if any help can be given that would be great!
You can add an object "addresses" to store all of your addresses, and then on a "change" event of an input field, get the row id and name of the field being changed, and then add it to the addresses object.
I added a basic example to your code, minus the sorting which was throwing a different error. Run the code snippet to see how it works.
$(document).ready(function() {
var addresses = {};
$(document).on('change', '#tab_logic input', function () {
var rowid = $(this).parents('tr').attr('id');
var name = $(this).attr('name');
// Initialize address row if it hasn't been created yet.
if (!addresses[rowid]) addresses[rowid] = {};
// Add or update this field.
addresses[rowid][name] = $(this).val();
console.log(addresses);
});
$("#add_row").on("click", function() {
// Dynamic Rows Code
// Get max row id and set new id
var newid = 0;
$.each($("#tab_logic tr"), function() {
if (parseInt($(this).data("id")) > newid) {
newid = parseInt($(this).data("id"));
}
});
newid++;
console.log(newid);
var tr = $("<tr></tr>", {
id: "addr"+newid,
"data-id": newid
});
// loop through each td and create new elements with name of newid
$.each($("#tab_logic tbody tr:nth(0) td"), function() {
var td;
var cur_td = $(this);
var children = cur_td.children();
// add new td and element if it has a nane
if ($(this).data("name") !== undefined) {
td = $("<td></td>", {
"data-name": $(cur_td).data("name")
});
var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
c.attr("name", $(cur_td).data("name") + newid);
c.appendTo($(td));
td.appendTo($(tr));
} else {
td = $("<td></td>", {
'text': $('#tab_logic tr').length
}).appendTo($(tr));
}
});
// add the new row
$(tr).appendTo($('#tab_logic'));
$(tr).find("td button.row-remove").on("click", function() {
$(this).closest("tr").remove();
});
});
});
$("#add_row").trigger("click");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Dropoff Locations -->
<div class=" mb-4">
<div class="card border-0 shadow">
<div class="card-body text-center">
<h5 class="card-title mb-0">Drop-Off Location(s)</h5>
<hr>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 table-responsive">
<table class="table table-bordered table-hover table-sortable" id="tab_logic">
<thead>
<tr>
<th class="text-center">
Street Address
</th>
<th class="text-center">
City
</th>
<th class="text-center">
State
</th>
</tr>
</thead>
<tbody>
<tr id='addr0' data-id="0" class="hidden">
<td data-name="name">
<input type="text" name='name0' placeholder='Street Address' class="form-control"/>
</td>
<td data-name="mail">
<input type="text" name='mail0' placeholder='City' class="form-control"/>
</td>
<td data-name="desc">
<input type="text" name="desc0" placeholder="State" class="form-control"/>
</td>
<td data-name="del">
<button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove'><span aria-hidden="true">×</span></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<a id="add_row" class="btn btn-primary float-right text-white">Add Stop</a>
I'm developing an application for users management with spring mvc. I'm using this bootstrap table in my jsppage which make me do a research on the data in the table .
In my table the data of users is retreived from database . this is the code :
<div class="col-md-9">
<form action="#" method="get">
<div class="input-group">
<!-- USE TWITTER TYPEAHEAD JSON WITH API TO SEARCH -->
<input class="form-control" id="system-search" name="q"
placeholder="Search for" required> <span
class="input-group-btn">
<button type="submit" class="btn btn-default">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</form>
<table class="table table-list-search">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Surname</th>
<th>email</th>
<th>contact</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<c:forEach items="${listUsers}" var="user">
<tbody>
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.surname}</td>
<td>${user.email}</td>
<td>${user.contact}</td>
<td>
<p data-placement="top" data-toggle="tooltip" title="Edit">
<button class="btn btn-primary btn-xs" data-title="Edit"
data-toggle="modal"
onclick="location.href='<c:url value="/modifier/${user.id}" />'">
<span class="glyphicon glyphicon-pencil"></span>
</button>
</p>
</td>
<td>
<p data-placement="top" data-toggle="tooltip" title="Delete">
<button class="btn btn-danger btn-xs" data-title="delete"
data-delete='${user.id}' data-toggle="modal"
data-target="#confirm-delete" data-href="/supprimer/${user.id}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</p>
</td>
</tr>
</tbody>
</c:forEach>
</table>
</div>
and this is the script which do the research on the table :
$(document).ready(function() {
var activeSystemClass = $('.list-group-item.active');
//something is entered in search form
$('#system-search')
.keyup(function() {
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table-list-search tbody');
var tableRowsClass = $('.table-list-search tbody tr');
$('.search-sf').remove();
tableRowsClass
.each(function(i, val) {
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if (inputText != '') {
$('.search-query-sf').remove();
tableBody
.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'
+ $(that).val()
+ '"</strong></td></tr>');
} else {
$('.search-query-sf').remove();
}
if (rowText.indexOf(inputText) == -1) {
//hide rows
tableRowsClass.eq(i).hide();
} else {
$('.search-sf').remove();
tableRowsClass.eq(i).show();
}
});
//all tr elements are hidden
if (tableRowsClass.children(':visible').length == 0) {
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
});
});
but when I've changed to dynamic table I have this result which make the word searching for : repeated n times !
I tried to change the code of the script but I failed to have the right script.
could some one help me please ?
It looks like this might be the problem
tableRowsClass.each(function(i, val) {
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if (inputText != '') {
$('.search-query-sf').remove();
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr>');
.each means that you're adding <tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr> to the start (because it's prepend) of your table, one for every element using .table-list-search tbody tr
try just moving tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr>'); outside of the .each() so that it only runs once.
I echo Jamie's answer, but I'd do a bit more refactoring.
I would move the searching out into its own function and pass the required rows collection and search string into it.
I would also move the check for search text outside the each loop, because the value is available outside the loop and doesn't change.
$(document).ready(function() {
var activeSystemClass = $('.list-group-item.active');
var searchTable = function(rows, searchStr){
var searching = false;
rows.each(function(i, val){
var rowText = $(val).text().toLowerCase();
if (rowText.indexOf(searchStr) == -1) {
//hide rows
rows.eq(i).hide();
} else {
$('.search-sf').remove();
rows.eq(i).show();
}
if (rows.children(':visible').length == 0) {
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
}
};
//something is entered in search form
$('#system-search')
.keyup(function() {
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table-list-search tbody');
var tableRowsClass = $('.table-list-search tbody tr');
var inputText = $(that).val();
$('.search-sf').remove();
if (inputText != ''){
$('.search-query-sf').remove();
searchTable(tableRowsClass, inputText.toLowerCase())
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "' + inputText + '"</strong></td></tr>');
}
});
});
An alternative to using javascript to create the repeating table row could be to use the hidden attribute and use javascript to remove that attribute whenever the .keyup event fires. You can then use javascript to set the value of a span tag with the search query. I couldn't get this example to work on jsFiddle or plunker, but i made an example. (this is pure raw JS with no styling)
<head>
<script type="text/javascript">
function doSearch(){
document.getElementById("searchingForRow").removeAttribute("hidden");
document.getElementById("searching").innerHTML = document.getElementById("system-search").value
}
</script>
</head>
<body>
<div class="col-md-9">
<div class="input-group">
<form>
<div>
<input id="system-search" placeholder="Search for" >
<button type="submit" class="btn btn-default" onclick="doSearch()">
Search
</button>
</div>
</form>
</div>
<table>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Surname</th>
<th>email</th>
<th>contact</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tr class="search-query-sf" id="searchingForRow" hidden>
<td colspan="6"><strong>Searching for: <span id="searching"></span></strong></td>
</tr>
<tbody>
<tr>
<td>An Example data this does nothing</td>
</tr>
</tbody>
</table>
this example, when the search button is clicked, removed the hidden attribute, making that row visible, and set's the span in the row to the value of the textbox.
it's essentially what you are trying to do.
with this method, it doesn't matter how many times the code to remove the hidden attribute is called, nothing will render more than once.
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..