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'>")
Related
I need to retrieve date from the generic input field. The number of how many date (input field) user can create in form is unknown by me, so I count them by rowCount.
I'm not enable to extract the value of field (Syntax error maybe).
N.B when I lunch my code I get: Cannot set property '0' of undefined
html code:
<div>
<table id='dynamic_field_edit'>
<tbody>
<tr>
<td>Date</td>
<td><input type="text" placeholder="Enter date" /></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" placeholder="Enter date" /></td>
</tr>
</tbody>
</table>
</div>
JS code :
var arrayDate = [];
var rowCount = document.getElementById('dynamic_field_edit').rows.length;
console.log(rowCount);
var allInputs = document.querySelectorAll('input');
for (let i = 0; i < allInputs.length; i++) {
arrayDate.push(allInputs[i].value);
}
console.log(arrayDate);
Edit:
After all suggested change it works, but it retrieve all values from input in document.
You just need to initialize your array:
var arrayDate = [];
EDIT:
Seems to work in this sample, can you compare to your code?
https://jsfiddle.net/emeLdecm/1/
(I added a button to fire off your JS, just to demonstrate)
Y you use jQuery syntax in plain javascript?
Select your table via:
table = document.getElementById('dynamic_field_edit');
and that iterate:
for (var i = 0, row; row = table.rows[i]; i++) {
// do your stuff
};
I find a way to achieve what I wanted to do by doing this.
#proggrock solution is also good for retrieving all input values in the document.
var arrayDate = [];
var rowCount = document.getElementById('dynamic_field_edit').rows.length;
console.log(rowCount);
$("#dynamic_field_edit").find('input:text')
.each(function() {
arrayDate.push($(this).val());
});
console.log(arrayDate);
I have a form like that:
<form>
<table id="table">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>SVNr</th>
</tr>
<tr>
<td contenteditable="true">Jill</td>
<td contenteditable="true">Smith</td>
<td class="svnr" contenteditable="true">50</td>
<td><input type="submit" value="Remove" onclick="DeleteRow(this)"></td>
</tr>
<tr>
<td contenteditable="true">Eve</td>
<td contenteditable="true">Jackson</td>
<td class="svnr" contenteditable="true">94</td>
<td><input type="submit" value="Remove" onclick="DeleteRow(this)"></td>
</tr>
</table>
<input type="button" value="Save Changes">
</form>
This one works perfectly. Futhermore, I want to add table rows to my table programmatically.
I do it this way:
count = numberOfRows;
formular[count] = new Object();
formular[count]["Firstname"] = document.getElementById("Firstname").value;
formular[count]["Lastname"] = document.getElementById("Lastname").value;
formular[count]["SVNr"] = document.getElementById("SVNr").value;
var table = document.getElementById("table");
var TR = table.insertRow(count);
var TD = document.createElement("td");
TD.setAttribute("contenteditable", "true");
var TD2 = document.createElement("td");
TD2.setAttribute("contenteditable", "true");
var TD3 = document.createElement("td");
TD3.setAttribute("contenteditable", "true");
TD3.className = "svnr";
var TD4 = document.createElement("td");
var TXT = document.createTextNode(formular[count]["Firstname"]);
var TXT2 = document.createTextNode(formular[count]["Lastname"]);
var TXT3 = document.createTextNode(formular[count]["SVNr"]);
var Input = document.createElement("input");
Input.type = "submit";
Input.value = "Remove";
Input.onclick = "DeleteRow(this);";
TD.appendChild(TXT);
TR.appendChild(TD);
TD2.appendChild(TXT2);
TR.appendChild(TD2);
TD3.appendChild(TXT3);
TR.appendChild(TD3);
TD4.appendChild(Input);
TR.appendChild(TD4);
document.getElementById("Firstname").value = "";
document.getElementById("Lastname").value = "";
document.getElementById("SVNr").value = "";
Also this code is working well. The only problem is that the Remove function doesn't work correctly for the table rows I added programmatically.
My Removing function looks like that:
function DeleteRow(o) {
var p = o.parentNode.parentNode;
p.parentNode.removeChild(p);
}
This function removes ALL programmatically added values if I press the button for one of them. This function works for the 2 entries in the form I didn't add programmatically but as I said, if I press the Remove button for one of added entries, it removes all programmatically added rows and not just the chosen one.
You need to add in something to uniquely identify each tr. You could set a custom attribute on each tr, set a unique id, etc. and pass the unique value to the delete function.
In addition you may find it easier to work with tables by using the DOMTable properties & methods:
http://www.javascriptkit.com/domref/tableproperties.shtml
http://www.javascriptkit.com/domref/tablemethods.shtml
I am trying to create a row of text boxes dynamically through Javascript and read the values of the textbox in JSON. Later,I have to read JSON and display the values in textarea and this should achieved only though jquery and javascript.
I am able to create the text boxes dynamically but I am unable to read the values in JSON. When I use the jQuery part(mentioned below),the javascript to dynamically create textboxes is not working.Any suggestions please.
<table id="myTable">
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Occupation and Employer</th>
<th>Add</th>
<tr>
<td><input type="text" id="txtName" /></td>
<td><input type="text" id="txtAge" /></td>
<td><input type="text" id="txtGender" /></td>
<td><input type="text" id="txtOccupation" /></td>
<td><input type="button" id="btnAdd" class="button-add" onClick="insertRow()" value="add"></input></td>
<td><input type="button" id="btnSave" class="button-add" value="Save"></input> </td>
</tr>
</table>
<script>
var index = 1;
function insertRow()
{
var table=document.getElementById("myTable");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
cell1.appendChild(t1);
var cell2=row.insertCell(1);
var t2=document.createElement("input");
t2.id = "txtAge"+index;
cell2.appendChild(t2);
var cell3=row.insertCell(2);
var t3=document.createElement("input");
t3.id = "txtGender"+index;
cell3.appendChild(t3);
var cell4=row.insertCell(3);
var t4=document.createElement("input");
t4.id = "txtOccupation"+index;
cell4.appendChild(t4);
index++;
}
$(document).ready(function(){
$("#btnsave").click(function ()
{
alert("Hi");
var dataToSend={
'Name':[],
'Age':[]};
dataToSend.Name.push({$("txtName").val().trim()});
dataToSend.Age.push({$("txtAge").val().trim()});
localStorage.setItem('DataToSend', JSON.stringify(DataToSend));
var restoredSession = JSON.parse(localStorage.getItem('dataToSend'));
// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
alert(restoredSession);
});
});
JSFIddle:http://jsfiddle.net/S7c88/
Since you are using jQuery you can greatly simplify the whole process by using methods like clone().
Here's a working example where I created one array of row objects. Since you aren't doing this in a form, I removed the ID's and just used data-name.
var $row;
function insertRow() {
$('#myTable').append($row.clone());
}
$(function () {
$row = $('tr').eq(1).clone(); /* clone first row for re-use*/
$('#myTable').on('click', '.btnSave', function () {
var dataToSend = [];
$('tr:gt(0)').each(function () {
var data = {};
$(this).find('input').each(function () {
data[$(this).data('name')] = this.value
});
dataToSend.push(data);
});
/* display data in textarea*/
$('#output').val(JSON.stringify(dataToSend, null, '\t'))
});
}) ;
I changed your input type=button to button to take advantage of using input selector while looping rows to create data and not have to filter out the buttons
Your demo has invalid html, missing <tr> for top set of <th>
DEMO
Some areas where you were going wrong:
$("txtName") Invalid selector
No row references in attempt to gather data
I am trying to get the values of multiple inputs on a page. The ids of the inputs are generated dynamically.
<input id="updates_662224305" class="text quantity" type="text" value="1" name="updates[662224305]" size="4">
I am running a loop for the table and cells in which the inputs are contained. I was getting the innerHTML of the cells the inputs are located in, and then slicing the section where their ids are:
var racetamarray = [],
racetamtotal = 0,
table = document.getElementById('cart-table'),
cells = table.getElementsByTagName('td');
for (var i=0,len=cells.length; i<len; i++){
if(cells[i].innerHTML.indexOf("ncombo-racetam") != -1) {
i+=3;
var racetaminput = cells[i].innerHTML;
var racetaminputcontain = racetaminput.slice(43,60);
var racetamelem = document.getElementById(racetaminputid);
racetamarray.push(parseInt(racetamelem.value));
}
}
This worked in firefox, as I was able to extract their ids and put them in the variable racetamelem. However when I tried it in chrome it does not work, the slice occurs at a different section of the string and does not capture their ids. Is there a better way to slice this or of converting the inputs from a string to a DOM element?
HTML of one of the rows in the table:
<tr class="item sampler-pramiracetam-capsules">
<td>
<span class="ncombo-racetam"></span>
<a href="/products/sampler-pramiracetam-capsules">
<img src="//cdn.shopify.com/s/files/1/0173/1766/products/PramiracetamCaps_grande_thumb.jpg?v=1396441752" alt="Sampler, Pramiracetam Capsules" />
</a>
</td>
<td>
Sampler, Pramiracetam Capsules - 30 Capsules</td>
<td>$8.90</td>
<td><input class="text quantity" type="text" size="4" id="updates_658967781" name="updates[658967781]" value="1" class="replace" /></td>
<td>$8.90</td>
<td><a class="btn remove-from-cart" href="/cart/change?id=658967781&quantity=0">Remove</a></td>
</tr>
This walks through the table rows and checks for any elements in the first cell with the class name, and if found then push the input value (from the fourth cell) to the array.
Demo: http://jsfiddle.net/SEaE4/
var racetamarray = [];
var table = document.getElementById('cart-table');
var row;
for(var i=0; i<table.rows.length; i++){
row = table.rows[i];
if(row.cells.length > 3){
if(row.cells[0].querySelectorAll('.ncombo-racetam').length) {
racetamarray.push(row.cells[3].getElementsByTagName('input')[0].value);
}
}
}
console.log(racetamarray);
Side note: if you need to support IE7 or older then you will need to replace the querySelectorAll() call with more code to check each element for the class.
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');
}
});