Insert new row, hide column in Javascript? - javascript

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');
}
});​

Related

How to make 1. space between text boxes created from javascript 2. align them with another text box from jsp

Please help me to solve two issues:
1. Make space between each additional textbox that is created from javascript
2. Align (from left at some position)the textboxes that are created from javascript with another textbox created from jsp
so basically, there is a textbox from JSP on the JSP page, when user clicks on Add button, the Javascript code adds additional textbox each time. I want the existing box from jsp and the addtional textboxes from javascript align at certain position from left and space between each textbox from javascript.
Thanks in advance
The Javascript and jsp code are below:
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.name = "choiceEntry";
element2.type = "text";
element2.size = "100";
cell3.appendChild(element2);
}
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) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
<html>
<form method="post" action="poll_save.jsp">
<TABLE id="dataTable" width="350px" border="0">
<TR>
<!-- <TD> 1 </TD>-->
<TD><INPUT type="text" class="bigText" value="
<%=choice.getChoiceEntry()%>" size = "100" name="choiceEntry"/> </TD>
<TD> <INPUT type="checkbox" name="chk"/></TD>
</TR>
</TABLE>
I'm not sure of what you want, but if you only want a vertical spacing and a left margin between inputs you'll be fine with this:
form[action="poll_save.jsp"] table input {
/* Your left offset here */
margin-left: 125px;
margin-top: 32px;
}
And for the code, add new inputs can be done in many ways, one might be:
const addOne = document.querySelector('#add-one');
const table = document.querySelector('#dataTable tbody');
let i = 0;
addOne.addEventListener('click', () => {
table.innerHTML += `
<tr>
<td>
<input name="input-${i++}" type="text" />
</td>
</tr>
`;
});
Perhaps you might want something more flexible? I mean like making them align to the center of their container? If that's the case, please provide a sketch of what you want to make it clearer.
Also my personal recommendation is that you move your style needs to css, do not leave them in the tags (Things such as <table width="..." ...>) and to not use IDs, or only IDs, I recommend you to add classes, specially for styling.
Here you have a working example: https://jsfiddle.net/sigmasoldier/kw8x3b42/2/
Note that there the JSP input is not written in JSP, but you can image that it has the JSP syntax.

How to separate each value for each textbox

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);
}
}

javascript setAttribute("name",newname) not change textbox's name it create submitName

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'>")

How to make this JavaScript code work in Opera

The following code works on the latest version of Firefox, Chrome, Safari and IE but not on Opera. When I click on the add button using Opera, a very thin space seems to have been added to row, but nothing else... Can anyone help?
The Form:
<form method="post" action="send.php">
<table id="table">
<tr><th>job</th><th>comment</th></tr>
<tr>
<td><textarea name = "job[]"></textarea></td>
<td><textarea name = "comment[]"></textarea></td>
<tr>
</table>
<input type ="button" value="add entry" onclick="add('table')"/>
<input type ="submit" id="submit" value="submit"/>
The JavaScript:
var names = ['job[]', 'comment[]'];
function add(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);
var newentry = document.createElement('textarea');
newentry.type = "text";
newcell.appendChild(newentry);
}
}
Setting newentry.type gives
Uncaught exception: DOMException: NO_MODIFICATION_ALLOWED_ERR
Actually, there is not type attribute of textarea, http://www.w3schools.com/tags/tag_textarea.asp. You would need the type if you would use input.
If you remove the line setting the type, it works good.
I also spotted another error in your code: you don't close the second row, but open a new one.
This is the good code:
<tr>
<td><textarea name = "job[]"></textarea></td>
<td><textarea name = "comment[]"></textarea></td>
</tr>
This line: newentry.type = "text"; causes an exception in Opera: Uncaught exception: DOMException: NO_MODIFICATION_ALLOWED_ERR. The line does nothing anyway (at least in Chrome), so I guess you can remove it.
var newentry = document.createElement('textarea');
newentry.type = "text";
console.log(newentry.type);
-> textarea
Use native DOM methods like .createElement to create TR(row) and TD(cells) which are supported across all browsers.
Your code might look as following:
var names = ['job[]', 'comment[]'];
function add(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.getElementsByTagName("TR").length;
var row = document.createElement("TR")
var colCount = table.getElementsByTagName("TR")[0].childNodes.length;
for (var i=0; i<colCount; i++) {
var newcell = document.createElement("TD");
row.appendChild(newcell);
var newentry = document.createElement('textarea');
newentry.type = "text";
newcell.appendChild(newentry);
}
}
table.appendChild( row );
}
I didn't test the above code, but it will help you to get there.

Dynamically add rows with jQuery autocomplete

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()).

Categories

Resources