Submit button setting a value in javascript - javascript

I have to make a button which has a value that is a javascript variable
<script>
for(i=0; i < count; i++)
{
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
cell.innerHTML = '<input type="submit" value=i onClick="someFunc(this.value)" />';
}
</script>
But when i open the page the value is just i. How do set the value of i in the button.

Wouldn't it just be
cell.innerHTML = '<input type="submit" value="'+ i + '" onClick="someFunc(this.value)" />';
so you use the value of i instead of the string i?

Here you are setting the value of button by wrong method..
<script>
for(i=0; i < count; i++)
{
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
cell.innerHTML = '<input type="submit" value='+i+' onClick="someFunc(this.value)" />';
}

if you assign i into quotes its take as a string. Not a variable. So u can use '+i+' .
+ Concatenation Operator
<script>
for(i=0; i < count; i++)
{
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
cell.innerHTML = '<input type="submit" value='+i+' onClick="someFunc(this.value)" />';
}
</script>

Related

rearrange/decrement row and cell id after deleting dynamically added rows javascript

I have a table with a default row and I am adding new rows dynamically with a button click, incrementing the ID of the tr and the innerText of the first td with a counter. I am trying to rearrange the ID's after deleting a row. Suppose I have 5 rows and I delete row nr 3, the 4th row should have the ID 3, and the 5th should have ID 4 etc. And also whena adding new rows it should rearrange the row ID's.
Here what I have so far. I have been trying but with no success or I dont get the desired results. Could anyone help me in the right direction?
<table class="table text-center table-borderless" id="rfqTable" style="font-size: 12px;">
<thead>
<tr>
<th>Item</th>
<th>Descr</th>
<th>Quantity</th>
<th>One Time</th>
<th>Supplier</th>
</tr>
</thead>
<tbody>
<tr id="1" class="tableRow">
<td class="item">1</td>
<td><textarea name="item[1]" rows="3" cols="90" maxlength="500"></textarea></td>
<td><input type="number" name="amount[1]"/></td>
<td><input type="checkbox" name="oneTime[1]" value="1"></td>
<td><input type="checkbox" name="supplier[1]" value="1"></td>
</tr>
</tbody>
</table>
Adding row:
var counter = 1;
var limit = 5;
document.getElementById("newItemBoxButton").addEventListener("click", function(){
if (counter == limit)
{
alert("Max row is 5!");
}
else
{
counter ++;
var table = document.getElementById("rfqTable");
var row = table.insertRow(-1);
row.setAttribute('id', counter );
var cell0 = row.insertCell(0);
cell0.innerHTML = counter;
cell0.setAttribute('id', 'item');
var cell1 = row.insertCell(1);
cell1.innerHTML = '<textarea name="item[' + counter + ']" rows="3" cols="90" maxlength="500"></textarea>';
var cell2 = row.insertCell(2);
cell2.innerHTML = '<input type="number" name="amount[' + counter + ']" style="width: 50px;"/>';
var cell3 = row.insertCell(3);
cell3.innerHTML = '<input type="checkbox" name="oneTime[' + counter + ']" value="1">';
var cell4 = row.insertCell(4);
cell4.innerHTML = '<input type="checkbox" name="supplier[' + counter + ']" value="1">';
var cell5 = row.insertCell(5);
cell5.innerHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
});
Deleting row:
function deleteRow(rowid)
{
var row = document.getElementById(rowid);
var table = row.parentNode;
while (table && table.tagName != 'TABLE')
{
table = table.parentNode;
if (!table)
{
return;
}
table.deleteRow(row.rowIndex);
counter--;
}
var table = document.getElementById('rfqTable');
var trRows = table.getElementsByTagName('tr');
var tdRows = table.getElementsByTagName('td');
for (var i = 0; i < trRows.length; i++)
{
trRows[i].id = counter;
}
for (var i = 0; i < tdRows.length; i++)
{
document.getElementById("item").innerText = counter;
}
}
After deleting a row, all the row id's turn into the same id, and the td item doesnt change at all.
In deleteRow function, why you have added this -
for (var i = 0; i < trRows.length; i++) {
trRows[i].id = counter;
}
You are assigning same value to all rows since your counter variable is not changing. It should be like this -
trRows[i].id = i + 1; // added + 1 since you want to start from 1 not 0
ok, I got a fix. I targeted the first column of every row and changed that value. For loop has to start at 1, else it will also target the first th. So now the IDs will be rearranged after deleting a row and the value will always start at 1.
var table = document.getElementById('rfqTable');
for (var i = 1; i < table.rows.length; i++)
{
var firstCol = table.rows[i].cells[0];
firstCol.innerText = i;
}

How do I output values from a javascript variable into an html td cell?

I have this function that generates a table where users can input numbers from 0-9.
function table(){
let strHTML = "";
strHTML = "<table>";
for(let row = 0; row< 9; row++){
strHTML += "<tr>";
for (let col = 0; col < 9; col++){
strHTML += `<td><input id=${row}-${col} type="number" min="0" max="9" /></td>`;
}
strHTML += "</tr>";
}
strHTML += "</table>";
document.getElementById('myTable').innerHTML = strHTML;
};
I have a function that saves the values from the HTML table in a javascript array.
function saveTable(){
for(let col = 0; col < 9; col++){
for(let row = 0; row < 9; row++){
sudokuArr[col][row] = Number(document.getElementById(col+"-"+row).value);
}
}
};
Finally I have this function which adds two numbers and displays it in a different cell. however whenever this function gets called nothing gets outputted. Not sure what I’m doing wrong?
function calculate(){
var x = sudokuArr[0][0];
var y = sudokuArr[0][8];
var k = x + y;
document.getElementById("0-1").innerHTML = k;
};
The element's id cannot begin with a number because it won't be recognized. Look at my example below: it throws an error with the id that starts with a number.
...an ID should start with a letter for compatibility.
Source: https://developer.mozilla.org/en/docs/Web/HTML/Global_attributes/id
document.querySelector('#c123').innerHTML = 'starts with a letter';
document.querySelector('#123c').innerHTML = 'starts with a number';
<div id="123c"></div>
<div id="c123"></div>
I've made some corrections to your code, you should be on your way.
var pref = 'X';
function table(){
let strHTML = "";
strHTML = "<table>";
for(let row = 0; row< 9; row++){
strHTML += "<tr>";
for (let col = 0; col < 9; col++){
strHTML += `<td><input id=${pref}${row}-${col} type="number" min="0" max="9" /></td>`;
}
strHTML += "</tr>";
}
strHTML += "</table>";
document.getElementById('myTable').innerHTML = strHTML;
};
table();
var sudokuArr = [];
function saveTable(){
for(let col = 0; col < 9; col++){
typeof sudokuArr[col] == 'undefined' && (sudokuArr[col] = []);
for(let row = 0; row < 9; row++){
sudokuArr[col][row] = Number(document.getElementById(pref + col+"-"+row).value);
}
}
};
saveTable();
function calculate(){
var x = sudokuArr[0][0];
var y = sudokuArr[0][8];
var k = x + y;
var el = document.getElementById(pref + "0-1");
el.value = k;
};
calculate();
<table id="myTable"></table>
Expanding on Josan's answer. Because you are setting the value of an input field, use document.getElementById("...").value. See snippet below for populating the grid.
Also, I would wrap the id in quotes to make things clearer. <td><input id="cell${row}-${col}" type="number" min="0" max="9" /></td>
function table(){
let strHTML = "";
strHTML = "<table>";
for(let row = 0; row< 9; row++){
strHTML += "<tr>";
for (let col = 0; col < 9; col++){
strHTML += `<td><input id="cell${row}-${col}" type="number" min="0" max="9" /></td>`;
}
strHTML += "</tr>";
}
strHTML += "</table>";
document.getElementById('myTable').innerHTML = strHTML;
};
function fill(){
var count = 1;
for(let col = 0; col < 9; col++){
for(let row = 0; row < 9; row++){
document.getElementById(`cell${row}-${col}`).value = count;
count++;
}
}
};
table();
fill();
<table id="myTable"></table>

Add counter to ID names in dynamically added rows

Here is part of a function that adds rows. It works like a charm, except I'd also like it to add an integer (+1) to the ID names of each newly created set of elements.
For example, the code below generates a row, a cell, and a button. If three rows are created, then I'd like the button ID's to be foo1, foo2, foo3 for each row, respectively.
How would I go about accomplishing this?
function addrow() {
var i = 1;
var table = document.getElementById("mytable");
var row = table.insertRow(1);
var cell1 = row.insertCell(1);
cell1.innerHTML = "<input type='button' id='foo+i' value='Hello'>";
i++;}
Thank you in advance!
Change:
cell1.innerHTML = "<input type='button' id='foo+i' value='Hello'>";
to:
cell1.innerHTML = "<input type='button' id='foo" + i + "' value='Hello'>";
Change
cell1.innerHTML = "<input type='button' id='foo+i' value='Hello'>";
to
cell1.innerHTML = "<input type='button' id='foo"+ i +"' value='Hello'>";
And initialize i value as global variable.
Use
var i = 1;
function addrow() {
var table = document.getElementById("mytable");
var row = table.insertRow(1);
var cell1 = row.insertCell(1);
cell1.innerHTML = "<input type='button' id='foo"+i +"' value='Hello'>";
i++;
}
You need to concat the string with your incremented variable, not place it inside the string.
"<input type='button' id=foo" + i +" value='Hello'>"
But there is more you need to do...
You need to make your i variable be global so it isn't reset every time you call this function like so
var i = 1;
function addrow() {
var table = document.getElementById("mytable"),
row = table.insertRow(i),
cell1 = row.insertCell(i);
cell1.innerHTML = '<input type="button" id=foo' + i + ' value="Hello">';
i++;
}
I also changed the quotes around since a single quote isn't considered valid syntax for HTML

How to append tds into tableRows?

I'm trying to append different <td>-elements to corresponding tr-elements, but no matter, what I am trying: it does not work :-/ Unfortunately I'm not able to show you an complete jsfiddle, because the whole table stuff is rather complex and depends on a map and stuff like that, but I hope some code snippets are also okay.
Table-Structure (header)
var table = createElement('table');
table.className = "table";
table.id = "table";
var header = table.createTHead();
var row = header.insertRow(0);
var cell0 = row.insertCell(0);
cell0.innerHTML = "Indicator"
var cell1 = row.insertCell(1);
cell1.innerHTML = "Current value"
var cell2 = row.insertCell(2);
cell2.innerHTML = "High value"
var cell3 = row.insertCell(3);
cell3.innerHTML = "Low value"
var cell4 = row.insertCell(4);
cell4.innerHTML = "Average";
var cell5 = row.insertCell(5);
cell5.innerHTML = "Pic";
tbody = table.appendChild(document.createElement('tbody'));
Then I'm using a for-loop, where the rest of the table is created:
//"key" is the description of the "value"
for (var key in values) {
//...
//method to calculate the values
...
//append values to tbody
$(table).find(tbody).append("<tr>");
$(table).find(tbody).append( "<td>"+(indicatorValue));
$(table).find(tbody).append( "<td>"+(regionValue));
$(table).find(tbody).append( "<td>"+(bestValues));
$(table).find(tbody).append( "<td>"+(worstValues));
$(table).find(tbody).append( "<td>"+(average));
//append image to a td-element
var img = "<img src='img/green_circle.png' />";
if (picIdentifier != 'green') {
img = "<img src='img/red_circle.png' />";
}
$(table).find(tbody).append( "<td>"+ img +"</td>");
}
Using the above code, the table looks like the following jsfiddle: http://jsfiddle.net/nwd6na53/2/
As you can see, the td-elements in the tbody are not wrapped in the tr-element, but the table-rows are empty.
Do you have any tip how to put the tds into the tr-elements? Any help is much appreciated!
Within your for loop, you need something more like this:
for (var i = 0; i <= 10; i++) {
var row = $('<tr></tr>');
$(row).append('<td>row ' + i + ', column1</td>');
$(row).append('<td>row ' + i + ', column2</td>');
$(row).append('<td>row ' + i + ', column3</td>');
$('#mytable').find('tbody').append(row);
}
Here's a fiddle with a code example:
https://jsfiddle.net/u2enny6o/3/
Note that I include complete tags in the append().
Better yet would be to use the insertRow() and insertCell() approach you use for the header section.
The answer of #Marc doesn't run well. See this
jsfiddle fail.
I think you should create a variable for an element tr. And append this tr to the tbody. For example, see this jsfiddle success :
var row = '<tr>' + '<td>' + indicatorValue + '</td><td>' + regionValue + '</td>' + '<td>' + bestValues + '</td></tr>';
$('table').find('tbody').append(row);

Dynamically creating an html table with Javascript

I am trying to create a table based on user input (actually two or three tables depending on the user input..) using Javascript, I am very much native to PHP and have already got this working in PHP, however i would like the user to be able to see the table before the query it. I found a script on here that partially did what I wanted and have attempted to edit it (I found it surprisingly similar to PHP) Basically it calculates the total amount of cells (ports) splits it by rows and columns, the "super" column is used if the user would like it to be split into multiple tables, which align next to each other, hence the div tag. Here's my JS:
<html>
<head>
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for(u=1; u<=num_row; u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
</script>
</head>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
Here is what the final output looks like after it has been processed by PHP (ports:24, col:6, rows:2, super:2):
Here is a js fiddle that I threw together:
http://jsfiddle.net/9SnLB/
Currently, when I click the button nothing happens, but, I suppose that is my first issue, but am I going about the setup correctly? Why wont the button run the function?
Two mistakes. One you didn't close the function bracket, ie a missing } at the end. The second is you used $row instead of the variable you created num_rows. For some reason it doesn't work in the fiddle, it does however work locally. The fiddle is saying the createTable function is undefined.
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for($u=1; $u<=num_rows; $u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}
var table = [["a1","a2","a3"]["b1","b2","b3"]["c1","c2","c3"]];
for(x = table.length;x > 0;x--) {
document.write("<tr>");
for(y = table[x].length;y > 0;y--) {
document.write("<td>"+y+"</td>");
}
document.write("</tr>");
}
Sorry if the syntax is wrong. You get the idea.
You need to change your jsFiddle framework to "no wrap (head)" and correct errors in the javascript. "no wrap (head)" will allow access the function. The "for ($u=1" loop is missing the close brace and $row should be num_rows. The "for (j=0" loop is missing a semicolon at the last "tbody=".
here's the corrected js.
function createTable() {
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for (var i = 0; i < num_super; i++) {
var theader = '<div><table border="1">\n';
for ($u = 1; $u <= num_rows; $u++) {
tbody += '<tr>';
for (var j = 0; j < colStart; j++) {
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>';
}
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}

Categories