How to read value of Textbox which is inside table - javascript

I need to read the value of textbox which is inside the table.
Following is how I create table.
var theader = '<table border = "1" id = "MarksTable">\n';
var tbody = '';
for ( var i = 0; i < total_rows; i++) {
tbody += '<tr>';
for ( var j = 0; j < total_col; j++) {
tbody += '<td name=' + "cell" + i + j + '>';
if (i > 0) {
tbody += '<input type="text" value = "marks" name="inputcell1'+j + '">';
} else {
tbody += '<b>' + subjectList[j] + '</b>';
}
tbody += '</td>';
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader
+ tbody + tfooter ;
and below is my attempt to read text box value:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].innerHTML;
}
}
return marks;
}
Here, row.cells[index].innerHTML gives the output '<input type="text" value = "marks" name="inputcell10">.

Try this:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].getElementsByName('inputcell' + index)[0].value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
return marks;
}

<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<div id="tableContainer">
</div>
<br>
<button onclick="myFunction()">Try it</button>
<button onclick="readTableData()"> Read it </button>
<script>
function myFunction() {
var tab = '<table id="MarksTable">';
var counter = 0;
for(i = 0; i< 4; i++){
tab = tab + '<tr><td rowspan = "4"> Dept1 </td><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
}
tab = tab + '</table>';
document.getElementById("tableContainer").innerHTML = tab;
}
function readTableData(){
var val;
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var rowcount = table.rows.length;
alert(rowcount);
if(column_count>0){
for(var index = 0; index < rowcount;index++){
var row = table.rows[index];
val = document.getElementById("inputcell"+index);
alert(val.value);
//marks = row.cells[0].getElementsByName('inputcell').value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
alert(val);
}
</script>
</body>
</html>

Related

Creating button in modal dialogue and run code in spreadsheet

I making a table and show it in the modal dialogue so that buttons will appear for each row in the table. My question is how to make the button in the modal dialogue run for specific row in spreadsheet? Example : click first button in first row in modal dialogue, will run and change data in first row of spreadsheet. Do I need to create specific ID for each buttons?
My GS code:
function leadRespond(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
var dataRange = sheet.getDataRange();
var dataValue = dataRange.getDisplayValues();
var temp = HtmlService.createTemplateFromFile("lead");
temp.data = {application : dataValue};
var html = temp.evaluate().setWidth(1200).setHeight(600);
SpreadsheetApp.getUi().showModalDialog(html,"Manage Leave");
}
HTML code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Leave Application</h1>
<div id="output"></div>
<script>
var output = document.getElementById("output");
window.onload = function (){
google.script.run.withSuccessHandler(onSuccess).getTable();
}
function onSuccess(data){
if(data.success){
console.log(data.data);
var html = '<table>';
var row;
for(var i=0; i<data.data.length; i++){
html += '<tr>';
row = i;
//console.log(row);
for (var j=0; j<9; j++){
html += '<td>'+ data.data[i][j]+'</td>';
}
html += '<td>'+ '<button onclick="approve()">Approved</button>'+'</td>';
html += '</tr>';
}
html += '</table>';
output.innerHTML = html;
console.log(data);
}
}
function approve(){
google.script.run.getRow();
console.log("test");
}
</script>
</body>
</html>
Code with google.script.run :
function getTable(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
var data = sheet.getDataRange().getDisplayValues();
Logger.log(data);
return {'success': true,'data':data};
}
function getRow(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
for (var i=0; i<dataValue.length; i++){
var row = "";
var rowNum;
for (var j = 0; j < 9; j++) {
if (dataValue[i][j]) {
row = row + dataValue[i][j]; //row = "" + range(0,0) [emailAddress], row = range(0,0)+ range(0,1)[emailAddress,Timestamp]
}
row = row + ",";
}
row = row + " Row num " + i;
rowNum = i;
Logger.log(row);
Logger.log(rowNum);
}
}
Use custom html-data attributes and delegate event to <table>:
html += '<td>'+ '<button data-row="'+i+'" data-column="'+j+'">Approved</button>'+'</td>';
//...
output.innerHTML = html;
console.log(data);
const table = document.querySelector("table");
table.addEventListener('click', approve);
}
function approve(e){
const td = e.target;
const [row, column] = [td.dataset.row,td.dataset.column];
google.script.run.modifyRows(row,column);
}

How can I use jQuery to randomly select one column from each row?

I have dynamically created rows and columns with jQuery. Can anyone help me on how to select a random column from each row? So far here is how my code looks like;
$(document).ready(function(){
var canva = $("#board");
var gameHolder = "<div class='gHolder'>";
var rows = 7;
var cols = 10;
function boardSetUp(){
for(var i = 0; i < rows; i++){
var row = "<div class='row'>";
for(var j = 0; j < cols; j++){
var col = "<li class='col'>";
col += "</li>";
row += col;
}
row += "</div>";
gameHolder += row;
}
gameHolder += "</div>";
canva.html(gameHolder);
}
boardSetUp();
})
You can use a comibnation of Math.floor() and Math.random() to get an integer between 1 and the amount of columns (x) per row.
Math.floor (Math.random () * x) + 1
I simplified your given example and added a funtion to select one random column per row. For this example I dynamically add a class for each selected column.
$(document).ready (function () {
var rows = 7;
var cols = 10;
var gameHolder = '';
for (var i = 0; i < rows; i++) {
gameHolder += '<div class="row">';
for(var j = 0; j < cols; j++)
gameHolder += '<div class="col"></div>';
gameHolder += '</div>';
}
$("#board").html(gameHolder);
})
function select_cols () {
var canvas = $("#board");
//reset all columns
$('.col').removeClass ('selected');
//loop through every row
canvas.find ('.row').each (function (i) {
//count columns and select random one
var count = $(this).find ('.col').size (); // $(this) is the current row
var selected = Math.floor (Math.random () * count) + 1;
//get your selected column-element
var column = $(this).find ('.col:nth-child(' + selected + ')') // :nth-child(x) is a css-selector
//do something with it. for example add a class
column.addClass ('selected');
});
}
#board {
border: 1px solid #999;
}
.row {
display: flex;
}
.col {
flex-grow: 1;
height: 10px;
border: 1px solid #999;
}
.selected {
background-color: #958;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board"></div>
<br>
<button onclick="select_cols ();">select random columns</button>
I see that you're asking for a random column for each row, but if you'd like just a random position on the game board, you could do something like this:
$(document).ready(function(){
var canva = $("#board");
var gameHolder = "<div class='gHolder'>";
var rows = 7;
var cols = 10;
function boardSetUp(){
for(var i = 0; i < rows; i++){
var row = "<div class='row'>";
for(var j = 0; j < cols; j++){
var col = "<li class='col' id='" + i + "-" + j + "'>";
col += "</li>";
row += col;
}
row += "</div>";
gameHolder += row;
}
gameHolder += "</div>";
canva.html(gameHolder);
}
boardSetUp();
function selectRandomLocation(){
var pos = $('#' + Math.floor(Math.random() * rows) + '-' + Math.floor(Math.random() * cols));
return pos;
}
})
you can use foreach and random ,
try :
var j = 0;
$("row").each(function(){
random_col = Math.floor(Math.random() * 10);
var i = 0;
$("li").each(function(){
if(random_col == i)
/* $(this) = your random col */
alert("the random col is a number "+i+" for col number "+j);
i++;
});
j++;
});

Table Issue in WYSIWYG Editor

I'm creating an HTML WYSIWYG editor from scratch and I have an issue when it comes to tables. Somehow, I'm able to create the pretended number of columns but only one row (without the heading). I'd be thankful if anyone could tell what's the issue.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Text Editor</title>
</head>
<body>
<div id="Ribbon">
<div id="Ribbon-3">
<button class="RibbonBtn" id="TableButton" title="Insert Table"><i class="fas fa-table"></i></button>
</div>
</div>
<div id="TextArea">
<div id="WYSIWYG" contenteditable="true"></div>
</div>
</div>
</body>
</html>
JS
window.addEventListener("load",function(){
$('#TableButton').click(function(){
var colnum = prompt("Indicate the number of columns");
var rownum = prompt("Indicate the number of rows");
var table = "";
var tablehead = "";
var tablebodytext = "";
for (var i = 0; i < colnum; i++) {
tablehead += "<th>null</th>";
}
var tablebody = [];
for (var i = 0; i < rownum; i++) {
var tablebodyrow = "";
for (var i = 0; i < colnum; i++) {
tablebodyrow += "<td>null</td>";
}
tablebody += "<tr>" + tablebodyrow + "</tr>";
}
table = "<table><tr>" + tablehead + "</tr>" + tablebody+ "</table>";
document.execCommand("insertHTML",false, table);
});
},false);
I chose 5 columns and 4 rows, but instead it created 5 columns and only 1 row
I've found the error. Such a dumb mistake...
I was using the same "i" var for the nested for loop and its parent loop.
This is the right version:
$('#TableButton').click(function(){
var colnum = prompt("Indicate the number of columns:");
var rownum = prompt("Indicate the number of rows:");
var table = "";
var tablehead = "";
var tablebodytext = "";
for (var i = 0; i < colnum; i++) {
tablehead += "<th>null</th>";
}
var tablebody = [];
for (var i = 0; i < rownum; i++) {
var tablebodyrow = "";
for (var i1 = 0; i1 < colnum; i1++) {
tablebodyrow += "<td>null</td>";
}
tablebody += "<tr>" + tablebodyrow + "</tr>";
}
table = "<table><tr>" + tablehead + "</tr>" + "<tbody>" + tablebody + "</tbody>" + "</table>";
document.execCommand("insertHTML",false, table);
});

How re-order rows when row is hidden

I want to be re-order the based on which field has been hidden, I set the hidden field zone zone_deleted to 1 when it it has been hidden to mark it as deleted.
function insertZone() {
var table = document.getElementById('zoneItems');
var e = document.getElementById('zone');
var number = e.options[e.selectedIndex].value;
var rowcount = document.getElementById('zoneItems').rows.length;
if(rowcount == 0){
var x = table.insertRow(-1);
var head1 = x.insertCell(0);
head1.innerHTML = "Zone";
var head2 = x.insertCell(1);
head2.innerHTML = "Motor Reference Point";
var head3 = x.insertCell(2);
head3.innerHTML = " ";
}
for (var i=0; i < number; i++)
{
var x = table.insertRow(-1);
var a = x.insertCell(0);
//a.innerHTML = "<input type='hidden' name='zone_id' value='' /> ";
num = i+1;
var b = x.insertCell(1);
b.innerHTML = "<input type='text' name='zone_description[]' size='18' value=''/><input id='zone"+num+"' type='hidden' name='zone_deleted[]' value='0' />";
var c = x.insertCell(2);
c.innerHTML = "<button type='button' class='button lastChild' onclick='removeZone(this)' ><img src='themes/default/images/id-ff-clear.png'></button>";
}
//set the row ordering
count();
}
function removeZone(rows) {
var _row = rows.parentElement.parentElement;
_row.cells[1].getElementsByTagName('input')[1].value = '1';
document.getElementById('zoneItems').rows[_row.rowIndex].style.display = 'none';
count();
}
function count(){ //sets the row ordering
var table = document.getElementById("zoneItems");
var tbody = table.tBodies[0];
for (var i = 0, row; row = tbody.rows[i]; i++) { //loop through rows
if(i != 0){//if not the first row
// var deleted = row.cells[1].getElementsByTagName('input')[1].value;
for (var j = 0, col; col = row.cells[j]; j++) {//loop through cols
if(j == 0){//insert into only the first td
col.innerHTML = "<span>" +i+ "</span><input type='hidden' name='zone_id' value='' />";
}
}
}
}
}
Use a different variable for the row number that's displayed than the one used to index the rows in the DOM.
function count() {
var table = document.getElementById("zoneItems");
var tbody = table.tBodies[0];
var rownum = 1;
for (var i = 1, row; row = tbody.rows[i]; i++) { //loop through rows
var deleted = row.cells[1].getElementsByTagName('input')[1].value;
if (deleted != "1") {
row.cells[0].innerHTML = "<span>" +rownum+ "</span><input type='hidden' name='zone_id' value='' />";
rownum++;
}
}
}
FIDDLE

JavaScript onclick programaticly not always works

I'm trying to set a onclick event handler.
from some reason this works:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function init() {
var td = document.getElementById("td");
var table = document.createElement("table");
var row = table.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "test";
cell.onclick = function () { alert(); };
td.appendChild(table);
}
</script>
</head>
<body id="td" onload="init()">
</body>
</html>
and when putting it in outside js file it doesn't work:
function buildChessBoard() {
var currentColor = white;
//var table = "<table>";
var table = document.createElement("table");
for (var i = 0; i < chessBoardsize / 8; i++) {
//table += "<tr>";
var row = table.insertRow(i);
for (var j = 0; j < 8; j++) {
//table += "<td class=" + currentColor + "Cell" + " id=" + (i * 8 + j) + " onclick=setCell(this)></td>";
var cell = row.insertCell(j);
cell.innerHTML = "test";
cell.onclick = function () { alert(); };
if (j != 7) {
if (currentColor == white)
currentColor = gray;
else
currentColor = white;
}
}
//table += "</tr>";
}
//table += "</table>";
//chessBoardDiv.innerHTML = table;
chessBoardDiv.appendChild(table);
}
any idea why ?

Categories

Resources