Javascript to add row in html table [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
In the below code i have html table in which i need to add row to html table and insert into database .But I couldn't add row.Pls help me to rectify the issue.My aim is to avoid postback so i choose javascript to add row .
<script language="javascript">
function addRow(tableID) {
var table = document.getElementById("<%=dataTable.ClientID%>").value;
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;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById("<%=dataTable.ClientID%>");
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
</script>
<input type="button" value="Add Row" onclick="addRow('dataTable')"/>
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')"/>
<table id="dataTable" width="350px" border="1" runat="server">
<tr>
<td><input type="checkbox" name="chk" runat="server"/></td>
<td><input type="text" name="txt" runat="server"/></td>
<td>
<asp:DropDownList ID="ddlProduct" runat="server" OnSelectedIndexChanged="ddlProduct_SelectedIndexChanged" AutoPostBack="true" Style="width: 100%; height:23px" ></asp:DropDownList>
</td>
</tr>
</table>

Theses lines are the problem:
var table = document.getElementById("<%=dataTable.ClientID%>").value;
var row = table.insertRow(rowCount);
Correct them to this:
var tableBody = document.getElementById("<%=dataTable.ClientID%>").getElementsByTagName("tbody")[0];
var row = tableBody .insertRow(rowCount);
Rows are inserted in a tablebody (tbody) and/or a tablehead (thead).
var table = document.getElementById("<%=dataTable.ClientID%>").value will return undefined. The value attribute is used only on inputs to retrieve or set the content of an input.

Related

Disable selected option of the first select box in the second select box

I want to find student's data by inserting their subject name and their score range. The teacher can add a new subject with an add button and can remove the subject too. Also the subject/option that has been already selected in the previous row will disable in the next new row.
Here is the html code
<button type="button" class="btn btn-bricky btn-sm" onclick="deleteRow('dataTable')"><span class="glyphicon glyphicon-remove"></span> Delete Row</button>
<table id="dataTable" class="table table-striped" style="font-size: 12px" >
<tr>
<td><input type="checkbox" name="chk"/></td>
<td>
<select name="subject" id="subject">
<option value="Math">Math</option>
<option value="Physic">Physic</option>
<option value="Chemistry">Chemistry</option>
<option value="Biology">Biology</option>
</select>
Score Min : <input type="number" name="comsMin" style="width:70px" min="0" max="100"/>
Max : <input type="number" name="comsMax" style="width:70px" min="0" max="100"/></td>
</tr>
</table>
And here is the JavaScript code
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;
}
}
}
//--------------
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
My problem is that I don't know how and where to write a code to disable the selected option that had been chosen in the first select box in the new added select box.
Is this possible?
Here's JS fiddle
We can have a separate table for storing the dataset in hidden mode and maintain the selection state in it.
Instead of hidden element you can also maintain the state in javascript variables.
function syncModdelAdd(tableID){
// Get the available selections
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var dataTable = document.getElementById('dataTable');
for(var i=0; i<rowCount; i++){
var selectedIndex = table.rows[i].cells[1].childNodes[1].selectedIndex;
dataTable.rows[0].cells[1].childNodes[1].options[selectedIndex].disabled=true;
}
}
function syncModelDelete(selectedIndex){
var dataTable = document.getElementById('dataTable');
dataTable.rows[0].cells[1].childNodes[1].options[selectedIndex].disabled=false;
var table = document.getElementById('resultTable');
var totalRows = table.rows.length;
table.rows[totalRows-1].cells[1].childNodes[1].options[selectedIndex].disabled=false;
}
Fiddle Link : https://jsfiddle.net/2tfacL9k/

Reset 1st Row with Add_row boutton

With the add button, the input will automatically be added next bellow row...if I want to reset 1st row after adding row bellow with the input value.How do I do this? if I input "a" in input box when I click add row button it will be appended but not reset 1st row
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[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = table.rows[1].cells[1].querySelector("input").value;
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
//clearForm();
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
<form action="#" method="post">
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<table id="dataTable" width="550px" border="1">
<tbody>
<thead>
<tr>
<th>Select </th>
<th>Name</th>
</tr>
</thead>
<tr>
<td><input type="checkbox" name="chk" /></td>
<td><input type="text" name="name"></td>
</tr>
</tbody>
</table>
</form>
I'm not exactly sure what you're asking. I played with your snippet and it seems like it's not clearing the input for the first row? I'm not sure what you're trying to accomplish either, maybe more context would be nice. Redrawing the table each time is a cheap operation until you start to get massive amounts of rows or data, so that is an option. If that's not viable, then I would maybe work on identifying the rows with an attribute and not just the index to make this table more scalable. If you don't, it's going to be hard to keep up with after you add more and more functionality.
The following resets the value of the first input when you add a new row. I'm not super sure why you'd want this functionality. It seems a little counter-intuitive for the end user, but nevertheless, here you go:
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[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch (newcell.childNodes[0].type) {
case "text":
var myInput = table.rows[1].cells[1].querySelector("input");
newcell.childNodes[0].value = myInput.value;
myInput.value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
//table.getElementsByTagName("td")[1].getElementsByTagName("input").value = "test";
//console.log(table.getElementsByTagName("td")[1].getElementsByTagName("input").value);
//clearForm();
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
<form action="#" method="post">
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<table id="dataTable" width="550px" border="1">
<tbody>
<thead>
<tr>
<th>Select </th>
<th>Name</th>
</tr>
</thead>
<tr>
<td><input type="checkbox" name="chk" /></td>
<td><input type="text" name="name"></td>
</tr>
</tbody>
</table>
</form>

jQuery autocomplete not working for multiple text inputs

I have the issue that autocomplete on works for the first textbox, but not for the other ones that I can add via a button. Here's my code:
HTML:
<input class="button" type="button" value="+" onclick="addRow('positionen')" />
<input class="button" type="button" value="-" onclick="deleteRow('positionen')" />
<table id="positionen">
<tr>
<td><input type="checkbox" name="chk[]" /></td>
<td><input class="ui-widget" type="text" name="text[]" placeholder = "Text" /></td>
<td><input type="text" name = "val[]" placeholder = "Val" /></td>
</tr>
</table>
Function addRow:
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;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}
Function deleteRow:
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Can't delete all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch(e) {
alert(e);
}
}
Autocomplete code:
$(function() {
$(".ui-widget").focusin(function(){
$(this).autocomplete({
source: 'search.php'
});
});
});
The first textbox that is already on the page by default is working fine with autocomplete. However when I add a textbox with the button, autocomplete is not working for this textbox.
Events are bind to the html when page is loaded, new rows are not there, you just need to bind it to the created rows by simply adding this to your addRow 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;
switch(newcell.childNodes[0].type) {
case "text":
if (newcell.childNodes[0].className === 'ui-widget ui-autocomplete-input') {
$(newcell.childNodes).autocomplete({
source: 'search.php'
});
}
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}

Adding/Removing row dynamically in html using javascript

I have this particular snippet..
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;
case "number":
newcell.childNodes[0].value = '';
break;
}
the switch above makes the newly added rows to reset the value from the copied row.
the text and number resets.
but the drop-down and checkboxes do not
what commands does these two need to reset their values?
for the dropdown, the first option and for the checkboxes is no box is checked
EDIT: this is the whole code
<script type="text/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[1].cells[i].innerHTML;
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;
case "number":
newcell.childNodes[0].value = '';
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[colCount-1].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
<body>
<label><input type="checkbox" id='checkboxId'>N/A</label>
<br>
<div id="div-table-id">
<table id='table-id' border="1">
<tr>
<th>Subject</th>
<th>Section Code</th>
<th>Room</th>
<th>Days</th>
<th>Start Time</th>
<th>End Time</th>
<th>Hours Per Week</th>
<th>No of Students (A)</th>
<th>Course Credit w/o multiplier(B)</th>
<th>Student Credit Units (AxB)</th>
<th>Teaching Load Credits with Multiplier</th>
<th>Delete?</th>
</tr>
<tr>
<td>
<select name="subject" >
<option value="cmsc2">CMSC2</option>
<option value="cmsc11" selected="selected">CMSC11</option>
<option value="cmsc121">CMSC121</option>
</select>
</td>
<td><input type="text" id="password" value="sample"/></td>
<td><input type="text" id="password2" value="sample"/></td>
<td>
<input type="checkbox" name="days" value="m" checked>M
<input type="checkbox" name="days" value="t">T
<input type="checkbox" name="days" value="m">W
<input type="checkbox" name="days" value="th">Th
<input type="checkbox" name="days" value="f">F
<input type="checkbox" name="days" value="s">S
</td>
<td><input type="time" name="start_time"></td>
<td><input type="time" name="end_time"></td>
<td><input type="number" name="hpw"></td>
<td><input type="number" name="nos"></td>
<td><input type="number" name="ccm"></td>
<td><input type="number" name="scu"></td>
<td><input type="number" name="tlcm"></td>
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<input type="button" value="Add Row" onclick="addRow('table-id')" />
<input type="button" value="Delete Row" onclick="deleteRow('table-id')"/>
<input type="button" value="Save"/>
</div>
<script>
document.getElementById('checkboxId').onchange = function () {
var elems = document.getElementById('div-table-id').querySelectorAll('input,select,textarea');
if (document.getElementById('checkboxId').checked) {
for (var i = 0; i < elems.length; i++) {
elems[i].disabled = true;
}
} else {
for (var i = 0; i < elems.length; i++) {
elems[i].disabled = false;
}
}
}
document.getElementById('password2').disabled = true;
document.getElementById('password').onblur = function(){
if(document.getElementById('password').value != '')
document.getElementById('password2').disabled = false;
else{
document.getElementById('password2').value = '';
document.getElementById('password2').disabled = true;
}
document.getElementById("password2").select();
}
document.getElementById('password2').onblur = function (){
if(document.getElementById('password').value == '')
return;
check();
}
function check() {
if (document.getElementById('password2').value != document.getElementById('password').value) {
alert('The two passwords must match.');
document.getElementById("password").select();
document.getElementById('password2').value = '';
}
else
alert('The two passwords matched.');
}
</script>
Ok, I figured out what your problem is. When you assign your new table cell's content to be the first row's content like so
newcell.innerHTML=table.rows[1].cells[i].innerHTML;
you copy along a bit of white space around your input/select elements sometimes which become text nodes. Thus your DOM will actually look like this in case of your SELECT element in the first TD:
[0] #Text node
[1] SELECT
[2] #Text node
This means when you grab the first child newcell.childNodes[0] you grab the Text node and the SELECT or CHECKBOX stays untouched.
I rewrote your code including a function that will reset all children of a new cell, as this also covers cases where someone checked more checkboxes in the first row which you use to append a new row.
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[1].cells[i].innerHTML;
resetChildren( newcell );
}
}
function resetChildren( parentEl ){
var len = parentEl.childNodes.length,
i = 0,
el;
for(i = 0; i < len; i++){
el = parentEl.childNodes[i];
console.log( i, el.type, el );
switch( el.type ){
case "text":
el.value = "";
break;
case "checkbox":
el.removeAttribute('checked');
break;
case "select-one":
el.selectedIndex = 0;
break;
case "number":
el.value = '';
break;
}
}
}

Using Jquery functions with Multiple Text Fields With Same ID

I looking for help on how to reference specific text fields with jquery that are generated with javascript.
What I get works only on the first instance of the field reference.
HTML Code:
Record ID<input type="text" name="ri[]" id="ri1" size="7" style="font-size:0.9em;">
Qty Per Box<input type="text" name="qpb[]" id="qpb1" size="7" style="font-size:0.9em;">
Javascript Used To Generate More Rows Like Above
<!--Dynamically Create New Rows For Data Entry-->
<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;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true === chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
So what I end up getting is multiple rows with the same id / name. What I simply want to do is validate input on keyup so I decided to use the (this).val method but it only works on the first row.
<script>
$(document).ready(function() {
$("#ri1").keyup(function() {
$(this).val($(this).val().replace(/[^\d]/g, ""));
});
});
</script>
Anybody know a better solution to validating input on when generating multiple rows of input fields this way?
Js fiddle http://jsfiddle.net/nS2LM/22/
Using an ID more than once is not recommended but if you are using the latest jQuery then event delegation is your answer:
<input type="text" name="ri[1]" id="ri1" size="7" style="font-size:0.9em;" class="do_stuff">
<input type="text" name="ri[2]" id="ri2" size="7" style="font-size:0.9em;" class="do_stuff">
<script>
$(document).ready(function() {
$('body').on('keyup', '.do_stuff', function() {
$(this).val($(this).val().replace(/[^\d]/g, ""));
});
});
</script>
The code above binds keyup to the body's child .do_stuff elements so any dynamically created elements with a class of .do_stuff will be caught by the keyup event.

Categories