i have a table with single row (textfield) and Add Row button, when user click on Add row, it dynamicaly create another row containing text field. Also i apply autocomplete on that text field.Now that autocomplete function work on first row correctly but when i add new rows it dosn't work. Below is my code plz tell me where i m wrong
Add row function
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
jQuery Auto-complete function
$(function() {
var availableTags = [
"Apple",
"Dell",
"Microsoft",
"Sony",
];
$( "#product" ).autocomplete({
source: availableTags
});
});
Add row button and table with text field
<input type="image" src="../images/add.png" onClick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD> <INPUT type="text" name="product" id="product" /> </TD>
</TR>
</TABLE>
Basically, what happened here was that the new element you created dynamically had not been picked up by the jQuery auto-complete function because it is created after you call that function. So what you need to do is calling the jQuery Auto-complete function each time after you add the row(at the end of function addRow()).
Related
I'm new to coding and I'm really stuck. Here's the situation: I made a script to generate a unique table from multiple text areas, and that’s working fine. The problem is that I need to fill the table in a specific way:
data from 1st textarea=1st Column
data from 2nd textarea=2nd Column
data from 3rd textarea=3rd Column
(but all the columns need to be part of the same table)
Right now all the data from the 3 textAreas appears one below the other(in rows, not columns) and I just can’t figure it out.
So far, that's my script:
<script>
function generateTable() {
$('textarea').each(function(){
var data = $(this).val(); console.log(data);
var rows = data.split("\n");
var table = $('<table />');
for(var y in rows) {
var cells = rows[y].split("\t");
var row = $('<tr />');
for(var x in cells) {
row.append('<td>'+cells[x]+'</td>');
}
table.append(row);
}
$('#excel_table1').append(table);
})
}
</script>
That’s my “body” with the text areas in divs:
<div id=street> <p>street:</p>
<textarea name="data1" style="width:100px;height:20px;"></textarea>
</div>
<div id=city> <p>city:</p>
<textarea name="data2" style="width:200px;height:20px;"></textarea>
</div>
<div id=country> <p>country:</p>
<textarea name="data3" style="width:100px;height:20px;"></textarea>
</div>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="Generate
table"/>
And that’s the table generated in a different "body":
<body><center>
<p>Table:</p>
<div id="excel_table1"></div>
</center></body>
Can Anyone help? The answer might be super easy, but I'm just trying to learn on the fly and know not much about JS! Thanks in advance :)
There can only be one <body> element on your page. So you would need to place both the textareas and the table in the same body element.
The problem with your script was that you created the table and appended it to your div for each textarea. You need to do this before and after iterating over the textareas.
I've created a snippet changing just that. Hope this helps!
function generateTable() {
var table = $('<table></table>');
$('textarea').each(function() {
var data = $(this).val();
console.log(data);
var rows = data.split("\n");
for (var y in rows) {
var cells = rows[y].split("\t");
var row = $('<tr />');
for (var x in cells) {
row.append('<td>' + cells[x] + '</td>');
}
table.append(row);
}
})
$('#excel_table1').append(table);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=street>
<p>street:</p>
<textarea name="data1" style="width:100px;height:20px;"></textarea>
</div>
<div id=city>
<p>city:</p>
<textarea name="data2" style="width:200px;height:20px;"></textarea>
</div>
<div id=country>
<p>country:</p>
<textarea name="data3" style="width:100px;height:20px;"></textarea>
</div>
<br>
<input id="bouton1" type="button" onclick="generateTable()" value="Generate
table" />
<p>Table:</p>
<div id="excel_table1"></div>
Never mind, I figured it out! :D
Here's the script that takes data from multiple textareas and put it in different columns of the same table:
<script src="jquery-3.5.0.js" type="text/javascript" charset="utf-8"></script>
<script>
function generateTable() {
var n=1;
var rows=[];
var lng=0;
$('textarea').each(function(){
var data = $(this).val();
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
n++;
})
var table = $('<table />');
k=0;
while (k < lng) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++) {
var singleRow = rows[i];
row.append('<td>'+singleRow[k]+'</td>')
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
It seems that when I try to retrieve a data for a certain id it populates it's data to all textbox present.
Here is my addrow script that adds a new row of textboxes:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
}
Here is my html file
<td><input type="text" name="personId" class="personId" size="30" onchange="test()"/></td>
<td><input type="text" name="personName" class="personName" size="30" disabled/></td>
Here is the test script which appends that data to the textbox:
function test(){
var $cell = $('.personId');
var cellData = $cell.html();
$cell.data('value', cellData);
//Code here to pass the personId in to an ajax and return it's corresponding personName
success: function(data) {
$('.personName').val(data.person);
}
}
What happens is that when I have 3 rows of personId and personName and I enter one personId all the textboxes in the 3 rows returns the personName. The goal is that when I enter an personId in one row pesonName should only reflect on the textbox i'm currently entering the personId. Please help. Thank you so much.
Follow the comments for understanding code.
var personVal =1; //personVal to create dynamic id
$(document).on('keyup','.personId', function() {
var personId = $(this).val();
//Code here to pass the personId to an ajax and return it's corresponding personName
//ajax success code here
//and success code like
// success: function(data) {
var currentPersonVal=this.id.split('-')[1];
var personName="#personName-"+currentPersonVal;
$(personName).val(currentPersonVal);//name hardcoded for your understanding, you need to add 'data.person'
//}
});
function addRow(tableID) {
var table = document.getElementById(tableID);
personVal =personVal+1 //increase personVal by 1
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
//generate textbox here with dynamic id by adding personVal at the end of id and '-'(dash) is used to split id later
var newcell = row.insertCell(0);
newcell.innerHTML = "<input type='text' id='personId-"+personVal+"' class='personId' size='30' />";
var newcell = row.insertCell(1);
newcell.innerHTML = "<input type='text' id='personName-"+personVal+"' class='personName' size='30' disabled/>";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table align="center" width="100%" id="table1Id" class = "centerAlign">
<td><input type="text" id="personId-1" class="personId" size="30" /></td>
<td><input type="text" id="personName-1" class="personName" size="30" disabled/></td>
</table>
<input type="button" value="Add Row" onclick="addRow('table1Id');"/>
Let me know if you don't understand anything.
You can give personId by data attribute like :
<td><input type="text" name="personId" data-personId = "1" class="personId" size="30" onchange="test()"/></td>
And then after that you can get that personId in like :
$('.personId').attr('data-personId');
In your html file change test() to test(this):
<td><input type="text" name="personId" data-personId = "1" class="personId" size="30" onchange="test()"/></td>
& change your test function to this :
function test(e){
// remove this
// var $cell = $('.personId');
var cellData = $(e).html();
$(e).data('value', cellData);
//Code here to pass the personId in to an ajax and return it's corresponding personName
success: function(data) {
$(e).closest('.personName').val(data.person);
}
}
i use this function to create a new row in table
function addRow(obj)
{
var table = document.getElementById("table2");
var rowCount = table.rows.length-1;
var row = table.insertRow(rowCount);
var nowrownum = table.rows.length-1;
var colCount = table.rows[2].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[2].cells[i].innerHTML;
newcell.style.cssText = table.rows[2].cells[i].style.cssText;
//Here is problem
newcell.childNodes[0].setAttribute("name",table.rows[2].cells[i].childNodes[0].getAttribute("name")+nowrownum);
//End here
newcell.childNodes[0].id = table.rows[2].cells[i].childNodes[0].id+nowrownum;
switch(newcell.childNodes[0].type)
{
case "text":
newcell.childNodes[0].value = "";
break;
}
}
obj.style.visibility = "hidden"; //to hide current button
}
Here is my html code
<form name=form id=form method=POST target="frametemp">
<table name ="table2" id="table2" border="1" align="Center">
<tr>
<th>Head1</th>
<th>Head2</th>
<th>Head3</th>
<th>Head4</th>
</tr>
<tr>
<td>xxxxx</td>
<td><input type="text" id="edit_0" name="edit_0" ></td>
<td>yyyy</td>
<td><input id="add_bt_0" onclick="JavaScript : addRow(this);" name="add_bt_0" value="addrow" type="button" ></td>
</tr>
after row is add i check the page from ie developer tool
<td><input type="text" id="edit_1" name="edit_0" submitName="edit_1" ></td>
<td><input id="add_bt_1" onclick="JavaScript : addRow(this);" name="add_bt_0" submitName="add_bt_1" value="addrow" type="button" ></td>
the name attribute does not change but it create submitName.
how can i make name attribute change.
my target brower is IE 7++(now i use ie 9)
How you change the id ..?? Use the same code to change the attribute name .. I mean
newcell.childNodes[0].name = table.rows[2].cells[i].childNodes[0].name + nowrownum;
They fixed this in IE8. In previous versions, you need to include the name when you call createElement. From MSDN:
Internet Explorer 8 and later can set the NAME attribute at run time
on elements dynamically created with the IHTMLDocument2::createElement
method. To create an element with a NAME attribute in earlier versions
of Internet Explorer, include the attribute and its value when using
the IHTMLDocument2::createElement method.
Here is the example from MSDN:
var newRadioButton = document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST'VALUE='First Choice'>")
I have a Javascript like this:
<script language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
}
}
}
var showMode = 'table-cell';
if (document.all) showMode='block';
function toggleVis(btn){
btn = document.forms['tcol'].elements[btn];
cells = document.getElementsByName('t'+btn.name);
mode = btn.checked ? showMode : 'none';
for(j = 0; j < cells.length; j++) cells[j].style.display = mode;
}
</script>
The following is HTML for show/hide the columns and insert new row:
<body>
<form name="tcol" onsubmit="return false">
Show columns
<input type=checkbox name="col1" onclick="toggleVis(this.name)" checked> 1
<input type=checkbox name="col2" onclick="toggleVis(this.name)" checked> 2
<input type=checkbox name="col3" onclick="toggleVis(this.name)" checked> 3
</form>
<input type="button" value="Insert Row" onclick="addRow('dataTable')">
<table id="dataTable">
<tr>
<td name="tcol1" id="tcol1"><input type="text" name="txt1"></td>
<td name="tcol2" id="tcol2"><input type="text" name="txt2"></td>
<td name="tcol3" id="tcol3"><input type="text" name="txt3"></td>
</tr>
</table>
I can insert row, but only the first row's column can be hidden. Is it because of the input fields' attributes? If yes, how do I add tag attribute into new row? Please help me out on this. Thanks.
newcell.innerHTML = table.rows[0].cells[i].innerHTML wont copy attribute to new cell, it will just copy innerHtml of table.rows[0].cells[i] cell.
So name attribute wont get applied to newcelll toggleVis functions work by finding cells by name attribute.
You can add following code in addRow to apply name attribute to newcell.
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
newcell.setAttribute("name",table.rows[0].cells[i].getAttribute("name"));//use setAttribute to set any attribute of dom element
newcell.style.display = table.rows[0].cells[i].style.display ; // to copy display style
newcell.id = table.rows[0].cells[i].getAttribute("name"); // IE workaround for getting this table cell in getElementsByName , see this http://stackoverflow.com/questions/278719/getelementsbyname-in-ie7
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
}
}
}
I know this doesn't answer your specific question, but your code needs a lot of help. The way you are doing things is very prone to breakage and can be accomplished in a much simpler way. Here is one example. I used jQuery to save myself time, but the principles can be mapped to plain javascript if you don't want to use jQuery.
Don't use inline javascript calls. You can monitor the parent container of the checkbox and determine which one was changed.
Don't monitor onclick events for checkboxes. Use onchange instead. This is safer.
You can use the html5 data attribute to store which checkbox was clicked. For example, <input type=checkbox name="col1" checked data-number="1"> 1.
Use the clicked data field to determine which cell in the table you want to modify.
http://jsfiddle.net/E3D2U/
$('input:checkbox').change( function() {
//which checkbox was changed?
var number = $(this).data('number') - 1;
//get the table cell that matches the clicked number
var targetTD = $('#dataTable td')[number];
//if our checkbox is checked then...
if ($(this).is(':checked')) {
$(targetTD).css('background-color', 'white');
}
else {
$(targetTD).css('background-color', 'yellow');
}
});
I'm delevoling an app with phonegap for android and I'm trying to make a FOR loop in javascript with html table rows. I tried using the document.write but all of the content in the page desapears, show just what it's in the document.write.
The code I have is this one:
<table id="hor-minimalist-b">
<script language=javascript>
for (var i=0; i<3; i++) {
document.write('<tr>');
document.write('<td>');
document.write('<input type="text" name="valor" id="valor" value="key' + i'">');
document.write('</td>');
document.write('</tr>');
}
</script>
</table>
Thanks.
It's because you are just putting text in the page, you need to "create" the element and append them to the table.
You can do it this way:
<table id="hor-minimalist-b"><thead></thead><tbody></tbody></table>
<script language="javascript">
var table = document.getElementById('hor-minimalist-b'); // get the table element
var tableBody = table.childNodes[1]; // get the table body
var tableHead = table.childNodes[0]; // get the table head
for (var i=0; i<3; i++) {
var row = document.createElement('tr'); // create a new row
var cell = document.createElement('td'); // create a new cell
var input = document.createElement('input'); // create a new input
// Set input properties
input.type = "text";
input.id = "valor"; // It's not a good idea (to have elements with the same id..)
input.name = "valor";
input.value = "key" + i;
cell.appendChild(input); // append input to the new cell
row.appendChild(cell); // append the new cell to the new row
tableBody.appendChild(row); // append the row to table body
}
</script>
insertRow() and insertCell() will probably work too, but I did not test it yet