Can't add datetimepicker in dynamically added table rows via JQUERY - javascript

I am working on a project where I am finding difficulty in adding datetimepicker to dynamically added table rows. I have added datetimepicker to static table rows and it is working fine for them but not working for dynamically added table rows.
The tutorial I am following for datetimepicker
https://eonasdan.github.io/bootstrap-datetimepicker/
My Code I tried: I am cloning hidden rows.
Row Clone function:
// Table Add Function
$('.table-add').click(function () {
var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
hid = $TABLE.find('tr.hide').attr('id');
// //Assigning every table row a unique ID
var max=0;
$('table').find('tr').each(function(){
var id=parseInt($(this).attr('id'));
if (id>=max){
max = id;
}
});
//cloning row with new ID
$clone.attr('id', parseInt(max)+1);
//always assign new id to new table row, will be easy to recognize rows
$clone.find('input.myinput').attr('id', parseInt(max)+1);
$clone.find("[name='datepicker']").datetimepicker();
//$("[name='datepicker']").datetimepicker();
$hiddentr = $('table').find('tr.hide');
//add dynamic word picker to cloned rows dynamically
$clone.find('td:nth-last-child(4)').after('{% if obj.word_picker == "Y" %} <td><input id="wordpicker" style="border:none"; data-role="tagsinput" class="myinput" name="unique_tag"/></td>{% endif %}');
$clone.appendTo( $('#'+hid).parent());
//submitting form after row clone
submitForm();
});
HTML of hidden td:
<td> <div style="position: relative"> <input class = "form-control" type= "text" name = "datepicker"
id= "datetime"></div> </td>

My guess... Is that the element has to be in the DOM to instantiate datetimepicker...
So keep the clone ID in a variable, so you can use it to lookup for the right datepicker element. Append the row. And finally instantiate datetimepicker.
// Table Add Function
$('.table-add').click(function () {
var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
hid = $TABLE.find('tr.hide').attr('id');
// //Assigning every table row a unique ID
var max=0;
$('table').find('tr').each(function(){
var id=parseInt($(this).attr('id'));
if (id>=max){
max = id;
}
});
//cloning row with new ID
var cloneID = parseInt(max)+1;
$clone.attr('id', cloneId);
//always assign new id to new table row, will be easy to recognize rows
$clone.find('input.myinput').attr('id', parseInt(max)+1);
$hiddentr = $('table').find('tr.hide');
//add dynamic word picker to cloned rows dynamically
$clone.find('td:nth-last-child(4)').after('{% if obj.word_picker == "Y" %} <td><input id="wordpicker" style="border:none"; data-role="tagsinput" class="myinput" name="unique_tag"/></td>{% endif %}');
$clone.appendTo( $('#'+hid).parent());
// Use the clone ID to instantiate datetimepicker
$("#cloneID").find("[name='datepicker']").datetimepicker();
//submitting form after row clone
submitForm();
});

Related

Add inputs from modal to a new table row using javascript

I have a modal with 2 input fields, and a table with two columns. I'm trying write a function that adds a new row to the table when a button is clicked. However when I test my code nothing happens.
The input fields have the id's "modal_type" and "modal_price", the table has the id "acc_table1"
JS:
{
var new_acc=document.getElementById("modal_type").value;
var new_bal=document.getElementById("modal_price").value;
var table=document.getElementsById("acc_table1");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='acc_row"+table_len+"'><td id='acc_name"+table_len+"'>"+new_acc+"</td><td id='acc_balance"+table_len+"'>"+new_bal+"</td></tr>";
document.getElementById("modal_type").value="";
document.getElementById("modal_price").value="";
}
I'd appreciate any suggestions on what I could change!
Try this:
const newRow = table.insertRow(-1); // appends a new row
newRow.itemId = 'acc_row'; // set item id to the new row
const accCell = newRow.insertCell(0); // add a cell to the new row at index 0
accCell.itemId = 'acc_name'; // set item id to the cell
const accText = document.createTextNode(new_acc); // create a text node for new_acc
accCell.appendChild(accText); // set text node to acc cell
const balCell = newRow.insertCell(1); // add a cell to the new row at index 1
balCell.itemId = 'acc_balance'; // set item id to the cell
const balText = document.createTextNode(new_bal); // create a text node for new_bal
balCell.appendChild(balText); // set text node to bal cell

issue with adding datetimepicker in dynamically added table rows

I am working on a project where I am finding difficulty in adding datetimepicker to dynamically added table rows. I have added datetimepicker to static table rows and it is working fine for them but not working for dynamically added table rows.
The tutorial I am following for datetimepicker
https://eonasdan.github.io/bootstrap-datetimepicker/
My Code I tried: I am cloning hidden rows.
Row Clone function:
// Table Add Function
$('.table-add').click(function () {
var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
hid = $TABLE.find('tr.hide').attr('id');
// //Assigning every table row a unique ID
var max=0;
$('table').find('tr').each(function(){
var id=parseInt($(this).attr('id'));
if (id>=max){
max = id;
}
});
//cloning row with new ID
$clone.attr('id', parseInt(max)+1);
//always assign new id to new table row, will be easy to recognize rows
$clone.find('input.myinput').attr('id', parseInt(max)+1);
$clone.find("[name='datepicker']").datetimepicker();
//$("[name='datepicker']").datetimepicker();
$hiddentr = $('table').find('tr.hide');
//add dynamic word picker to cloned rows dynamically
$clone.find('td:nth-last-child(4)').after('{% if obj.word_picker == "Y" %} <td><input id="wordpicker" style="border:none"; data-role="tagsinput" class="myinput" name="unique_tag"/></td>{% endif %}');
$clone.appendTo( $('#'+hid).parent());
//submitting form after row clone
submitForm();
});
HTML of hidden td:
<td>
<div style="position: relative">
<input class = "form-control" type= "text" name = "datepicker" id= "datetime">
</div>
</td>
Messy but just init datetimepisker each time after you add a row...
$('#datetimepicker1').datetimepicker();
$('#datetimepicker2').datetimepicker();
etc
I was able to initialize the datetimepicker once the element was completely generated into the dom. working codepen
function addTableRow() {
var tbodyElement = document.getElementById("tbody");
var trElement = document.createElement("tr");
trElement.id = "generatedTr";
for (var x=0; x<3; x++) {
var tdElement = document.createElement("td");
var textNode = document.createTextNode("Generated td: " + x);
tdElement.appendChild(textNode);
trElement.appendChild(tdElement);
}
var finalTdElement = document.createElement("td");
var inputElement = document.createElement("input");
inputElement.setAttribute("type", "text");
inputElement.id = "generatedInput";
finalTdElement.appendChild(inputElement);
trElement.appendChild(finalTdElement);
tbodyElement.appendChild(trElement);
$('#generatedInput').datetimepicker();
}
If you have multiple elements that are being generated that needs the datetime picker, then I would suggest creating a class on all of them, then simply instantiate the plugin against that class like so.
$('.dateTimePickers').datetimepicker();
I would suggest don't initialize the datetimepicker every time after each element. better use following code. It will work like a charm.
I have been doing lot of research for this. Thus, Recommending to use Following code.
$('body').on('focus',".datetimepicker", function(){
$(this).datetimepicker();
});

Show a table (number of rows variable) on a div after click button? Works until some point

(This is my first question here and I am new to programming)
I am stuck on a problem and I tried to take something from here:
http://jsfiddle.net/4pEJB/
Dynamically generated table - using an array to fill in TD values
The function I created receive two vectors and creates a table with 2 columns, one for each vector, and lines = vector.length.
The function works fine, it seems to create the table as I need, but it doesn't show the table created on the browser screen after button click. By using some 'alert()' on the for loops I was able to verify that it uses the correct data.
In fact, when the button is clicked, it calls another function that processes some data and passes two vectors on this function I am showing here, but this part works well.
Here is the HTML part:
<div class="tableDiv">
<input type="button" onclick="createtable([1,3,5,7,9],[2,4,6,8,10])" value="Show data">
</div>
And here is the JavaScript part:
function createtable(vet_1,vet_2){
var tableDiv = document.getElementById("tableDiv");
var table = document.createElement("table");
var tableBody = document.createElement('tbody');
for (var r=0;r<vet_1.length;r++){
var row = document.createElement("tr");
for (var c=0;c<2;c++){
var cell = document.createElement("td");
if (c==0){cell.appendChild(document.createTextNode(vet_1[r]));}
else if(c==1){cell.appendChild(document.createTextNode(vet_2[r]));}
row.appendChild(cell);
}
tableBody.appendChild(row);
}
tableDiv.appendChild(table);
}
When the function finishes the table feed, it stops on tableDiv.appendChild(table);
Any advice or suggestions will be greatly appreciated! (I speak portuguese, I am sorry for some errors)
EDIT: it's possible to avoid the increment on the number of table rows that occurs every time we click the button (the solution provided generates one new table under the previous table). To solve this, I just added this line on the beggining of the function code (need to put the button outside the div and let the div empty, otherwise it will hide the button):
document.getElementById("tableDiv").innerHTML = "";
you are capturing by id, but you set up a class.chang it to id
<div id="tableDiv">
and append the tableBody into table.You're populating the table body with rows, but never appended the body into the table element.
function createtable(vet_1,vet_2){
var tableDiv = document.getElementById("tableDiv");
var table = document.createElement("table");
var tableBody = document.createElement('tbody');
for (var r=0;r<vet_1.length;r++){
var row = document.createElement("tr");
for (var c=0;c<2;c++){
var cell = document.createElement("td");
if (c==0){cell.appendChild(document.createTextNode(vet_1[r]));}
else if(c==1){cell.appendChild(document.createTextNode(vet_2[r]));}
row.appendChild(cell);
}
tableBody.appendChild(row);
}
table.appendChild(tableBody) // append tableBody into the table element
tableDiv.appendChild(table);
}
<div id="tableDiv">
<input type="button" onclick="createtable([1,3,5,7,9],[2,4,6,8,10])" value="Show data">
</div>
You try to append the var table to the tableDiv but the var table is stil empty.
Before append the tableBody to the var table and it will work.
Use id instead of class in your HTML Markup
<div id="tableDiv">
and then use the following code.
function createtable(vet_1,vet_2){
var tableDiv = document.getElementById("tableDiv");
var table = document.createElement("table");
var tableBody = document.createElement('tbody');
for (var r=0;r<vet_1.length;r++){
var row = document.createElement("tr");
for (var c=0;c<2;c++){
var cell = document.createElement("td");
if (c==0){cell.appendChild(document.createTextNode(vet_1[r]));}
else if(c==1){cell.appendChild(document.createTextNode(vet_2[r]));}
row.appendChild(cell);
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
tableDiv.appendChild(table);
}
First you are accessing the div using id whereas the node is defined with a class.
Secondly, you have to append the body to the table node first, and then append the table to the div selected.
Try this code snippet to move on.

I need the id and name of inner element when cloning a row of a table with javascript

When hitting areasensornewline_button, a new row gets created and appended to the table. I can change the row ID, but all new dropdownboxes within this row now have id="selectedArea0", id="selectedSensor0" and name="AreaBinding0", name="sensorBinding0". These have to be 1, 2 and so fort. Any help would much be appreciated!!!!
<table border="0" id="areasensor_table">
<tr id="areasensor_row0">
<td id="area_column0">
<select name="areaBinding0" id="selectedArea0"> #for(area <- areas) {
<option value="#area.uniqueid">#area.name</option>}
</select>
</td>
<td id="sensor_column0">
<select name="sensorBinding0" id="selectedSensor0"> #for(sensor <- sensors) {
<option value="#sensor.id">#sensor.name</option> }
</select>
</td>
<td>
<a class="glyphicon glyphicon-plus" id="areasensornewline_button"></a>
</td>
</tr>
</table>
<p>
<p>
<script>
var q = 1;
document.getElementById('areasensornewline_button').onclick = cloneRowAreaSensor;
function cloneRowAreaSensor() {
var row = document.getElementById('areasensor_row0'); // find row to copy
var table = document.getElementById('areasensor_table'); // find table to append to
var clone = row.cloneNode(true); // copy children too
var innerClone = row.innerHTML;
clone.id = 'areasensor_row' + q; // change id or other attributes/contents
q++;
table.appendChild(clone); // add new row to end of table
}
</script>
A trick is to use Regular expression but is far to be perfect ...
function cloneRowAreaSensor() {
var row = document.getElementById('areasensor_row0'); // find row to copy
var table = document.getElementById('areasensor_table'); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.innerHTML = clone.innerHTML.replace(/0"/g, q + '"');
clone.id = 'areasensor_row' + q; // change id or other attributes/contents
q++;
table.appendChild(clone); // add new row to end of table
}
The added row is placed outside the tbody html tag. You really should use jQuery, il will help you a lot.
Your code only works first time. Create a counter use it to name element.
Example:
var count = 1;
for(i = 0; i<= 10; i++){
var row = document.getElementById('areasensor_row'+ count +'');
}
It is a simple example. You need to restructure your code like this example. (This cicle for isnt better example, but it works at 10 elements)

jQuery to select next table row

I have two rows of a table here. When I click the checkbox in the first table row, I'm trying to target the ID of the span in the next table row. I have an alert in my code just to show me that I was successful.
What I have isn't working. I can't figure out a way to select data in the next table row when the checkbox in the first row is clicked.
<table>
<tr id="row-a">
<td>
<input type="checkbox">
<span>
some text
</span>
</td>
</tr>
<tr>
<td>
<span id="target">
some text
</span>
</td>
</tr>
</table>
$(document).ready(function() {
var myCheck = $("tr#row-a td input");
myCheck.change(function(){
var spanID = $("tr#row-a').next('tr').find('span').attr('id');
alert(spanID);
});
});
Try this:
var myCheck = $("tr#row-a td input");
myCheck.change(function(){
var spanID = $(this).closest('tr').next().find('span').attr('id');
alert(spanID);
});
Example fiddle
$(document).ready(function() {
var myCheck = $("tr#row-a td input");
myCheck.change(function(){
var spanID = myCheck.parents("tr").next().find('span').attr('id');
alert(spanID);
});
});
The change was in this line:
var spanID = myCheck.parents("tr").next().find('span').attr('id');
Which does the following:
Finds the checkbox's tr parent
Gets the next sibling node (next tr)
Finds the span
Gets its id

Categories

Resources