I want to generate click able table grid using javascript.
My code is not working.
I created 2 text input fields for get values for row and column.
Button that will call drawGrid() function onClick event.
<input type="text" name="enter" class="enter" value="" id="inputX"/>
<input type="text" name="enter" class="enter" value="" id="inputY"/>
<input type="button" value="click" onclick="drawGrid();"/>
<script language="JavaScript">
function drawGrid(){
document.write('<table border="1">');
var x_start = 1;
var x_end = document.getElementById('inputX').value;
var y_start = 1;
var y_end = document.getElementById('inputY').value;
// loop over all x values (rows) sequentally
for( var x=x_start; x <= x_end; x++ ){
// open the current row
document.write('<tr>');
// loop over all y values (cols) sequentally
for( var y=y_start; y <= y_end; y++ ){
// write out the current x/y coordinate with a table cell
document.write('<td> x:'+x+' y:'+y+'</td>');
}
// end the current row
document.write('</tr>');
document.write('</table>');
}
}
</script>
First, a couple of points I think are worth making:
document.write is not the best tool for this job.
(and far more serious) Have a look again at your nested for-loops.
You perform the outside loop width number of times. In this loop you create a new row, add some cells, close the row and then close the table.
Read #2 again - that's right, you try to make width number of rows instead of height number of rows. You also finish the table each row (yet only start the table once)
Here's some code that uses the ability to create elements with JS objects (a opposed to js-created text strings)
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('goBtn').addEventListener('click', onGoBtnClicked, false);
}
function onCellClicked(evt)
{
alert( this.innerHTML );
}
function onGoBtnClicked(evt)
{
byId('tblTgt').innerHTML = '';
var nCols = byId('inputX').value;
var nRows = byId('inputY').value;
var tbl, curRow, curCell;
tbl = newEl('table');
var x, y;
for (y=0; y<nRows; y++)
{
curRow = newEl('tr');
tbl.appendChild(curRow);
for (x=0; x<nCols; x++)
{
curCell = newEl('td');
curCell.addEventListener('click', onCellClicked, false);
curCell.innerText = "[" + x + "," + y + "]";
curRow.appendChild(curCell);
}
}
byId('tblTgt').appendChild(tbl);
}
</script>
<style>
</style>
</head>
<body>
nCols:<input type="text" name="enter" class="enter" value="" id="inputX"/><br>
nRows:<input type="text" name="enter" class="enter" value="" id="inputY"/><br>
<button id='goBtn'>click</button>
<hr>
<div id='tblTgt'></div>
</body>
</html>
Related
i'm making a web application which helps people to seek what disease they have according to the symptoms.
I want to the user to click specific symptom to add in the "u_symptom_i" array and show all of the changed array elements by alert function
However, i cannot see the added element by alert function
<script>
var j = 0;
while(j < escaped_cc.length) {
document.write('<th><button id="symptom_button">' + escaped_cc[j] + '</button></th>');
document.getElementById("symptom_button").value = escaped_cc[j];
j = j + 1;
}
$("button").click(function() {
u_symptom_i.push($(this).val());
alert($(this).val());
});
</script>
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
<h2>Insert Array</h2>
<input type="text" id="example" name="value">
<button id="button">Add array new item</button>
</body>
<script>
var array=[];
$("#button").click(function() {
var str = $("#example").val();
array.push(str);
alert(array);
});
</script>
</html>
Can you try this code? Adds each new value entered to an array named array and displays the records.
I have a table generated from a textarea filled by users, but some of the time, a cell stays empty (and that's all right).
The thing is that the .innerHTML of that cell is also my var y in a script and when that cell is empty (therefore, undefined), my var y becomes UNDEFINED too (the value, not a string), which makes my whole script fail.
Here's a snippet to show the problem:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><center>
</center></body>
<!--------- script that generates my table from text areas -->
<script>
function generateTable() {
$('#excel_table1').html("");
var n=1;
var rows=[];
var lng=0;
var maxligne=0;
$('textarea').each(function(){
var data = $(this).val();
if (data !=''){
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
if(lng > maxligne)
{
maxligne=lng
}
n++;
}
}
)
var table = $('<table />');
k=0;
while (k < maxligne) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++)
{
var singleRow = rows[i];
if(singleRow[k]!= undefined){
row.append('<td>'+singleRow[k]+'</td>')
} else {
row.append('<td></td>')
}
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
<textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea>
<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
<textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
<div id="excel_table1"></div>
<!--------- script that get the data from cells to show it in <H2> -->
<script type="text/javascript">
function buttonTEST()
{
$('#displayCell').html("");
var x = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[1].innerHTML;
var y = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[2].innerHTML;
if (y === undefined) {
y = " ";
}
document.getElementById('displayCell').innerHTML = x +" "+ y;
}
</script>
<br/><br/>
<h2 id="displayCell"></h2>
<br/><br/>
<input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>
As you can see, if you generate a table with only to columns (which is supposed/needs to happen sometimes), we get this error from the console because we're trying to get "innerHTML" from a undefined:
index.html:120 Uncaught TypeError: Cannot read property 'innerHTML' of undefined
A little specification: When that cell is=undefined , I need it to stay undefined, I only want to change the fact that my var y also becomes undefined.
So I thought that changing the value of var y (and not the value of that cell, otherwise, the 3rd column, supposed to be empty, would be created just because of an blank space) to a blank space would resolve the problem, but I don't seem to get it right (write it in a correct manner).
Any ideas?
Try
var x = document.getElementById('excel_table1').rows[0].cells[0].innerHTML;
var y = document.getElementById('excel_table1').rows[0].cells[1].innerHTML;
using rows instead of getElementsByTagName is cleaner.
Also note that the indexes for cells start from zero not 1, you probably only have 2 cells in your first row, but .cells[2].innerHTML tries to get the innerHTML of the 3rd cell which does not exist.
As others have pointed out, you're already using jQuery, so the easiest way to get the cell contents is to use a css selector to find the cells using the $ function, then call .html() to get the contents. A direct conversion of your current code to this approach could be:
var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
This works in a way so that the $ function returns a jQuery object, which is essentially a set of elements, which can potentially be empty. Most jQuery functions are then designed to fail gracefully when called on an empty set. For instance, html will return undefined when invoked on an empty set, but it will not fail.
Note that it is not very robust to use the selector above, as it is obviously sensitive to the placement of the cells. It would be more maintainable to assign a class attribute to the cells that describes their content, and then select on that, e.g. something like
var name = $("#excel_table1 tr:nth-child(1) td.name").html()
So here's the answer that worked for me:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><center>
</center></body>
<!--------- script that generates my table from text areas -->
<script>
function generateTable() {
$('#excel_table1').html("");
var n=1;
var rows=[];
var lng=0;
var maxligne=0;
$('textarea').each(function(){
var data = $(this).val();
if (data !=''){
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
if(lng > maxligne)
{
maxligne=lng
}
n++;
}
}
)
var table = $('<table />');
k=0;
while (k < maxligne) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++)
{
var singleRow = rows[i];
if(singleRow[k]!= undefined){
row.append('<td>'+singleRow[k]+'</td>')
} else {
row.append('<td></td>')
}
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
<textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea>
<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
<textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
<div id="excel_table1"></div>
<!--------- script that get the data from cells to show it in <H2> -->
<script type="text/javascript">
function buttonTEST()
{
$('#displayCell').html("");
var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
if (y ===undefined)
{document.getElementById('displayCell').innerHTML = x ;}
else
{document.getElementById('displayCell').innerHTML = x +" "+ y;}
}
</script>
<br/><br/>
<h2 id="displayCell"></h2>
<br/><br/>
<input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>
How would you start writing a for loop for the code provided below:
<html>
<head>
</head>
<body>
Rows: <input name="rows" id="rows" type="text"/><br/>
<input type="submit" value="Make me a table!" onclick="makeTable();"/><br/><br/>
<table border="1" id="theTable">
</table>
<script type="text/javascript">
function makeTable(){
//Insert code here AND ONLY HERE!
//Write a for loop to create the number of rows specified in the "row" input field
</script>
</body>
</html>
As I suspect this is homework I will no provider a full code answer but instead provide you with a few guide lines that hopefully will help you.
You have the html and the javascript, in order to create new html elements you need to use the document.createElement(type) function that will create a new element, in your case - td/th ?
Then you need to insert it into your table
You do that by obtaining the table(by id/type) - search the web for this one its very simple.
And then using the append method on is with the created element.
You do all this process with a normal for loop that will run until the .value of the input tags you have in your html (Again, search for how to obtain these values)
Good luck =]
Is this what you are looking for?
function makeTable(){
// Get values of rows/cols inputs
var rows = document.getElementById('rows').value;
var cols = document.getElementById('cols').value;
// Check the values are in fact numbers
if (!isNaN(rows) && !isNaN(cols)) {
// Get the table element
var table = document.getElementById('theTable');
// Iterate through rows
for (var r = 0; r < rows; ++r) {
// Create row element
var tr = document.createElement('tr');
// Iterate through columns
for (var c = 0; c < cols; ++c) {
// Create cell element
var td = document.createElement('td');
// Setting some text content
td.textContent = 'R: ' + r + ', C: ' + c;
// Append cell to row
tr.appendChild(td);
}
// Append row to table
table.appendChild(tr);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
Rows: <input name="rows" id="rows" type="text"/><br/>
Cols: <input name="cols" id="cols" type="text"/><br/>
<input type="submit" value="Make me a table!" onclick="makeTable();"/> <br/><br/>
<table border="1" id="theTable">
<script type="text/javascript">
function makeTable(){
var html = "";
var row=$('#rows').val();
var col=$('#cols').val();
for(var i=0; i<row; i++){
html+="<tr>";
for(var j=0;j<col; j++)
{
html+= '<td> Your data </td>';
}
html+="</tr>"
}
$('#theTable').html(html);
//Insert code here AND ONLY HERE!
//Write a for loop to create the number of rows specified in the "row" input field
//create a dom element for the row to be added to the table
}
</script>
</body>
</html>
I have kept it simple. Hope it helps.
I have a JSC3D scene that contains multiple files. My goal would be to show/hide one of the models with an onClick call.
The two options I can come up with are to recreate the scene with the one model missing, or to somehow access a visible property of one of the models.
I've tried various permutations of the alert code to access the visible property, but no luck there. The updateview function was my attempt to recreate the scene with the missing model. BTW, if you change colors[newLoaded] to colors[newLoaded+1] the colors will update, but the displayed models remain the same.
It has been many years since I looked into this stuff so I am sure it is something easy that I am missing
Thanks
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>Crown Study Ranking</TITLE>
<script type="text/javascript" src="jsc3d/jsc3d.js"></script>
<script type="text/javascript" src="jsc3d/jsc3d.webgl.js"></script>
<script type="text/javascript" src="jsc3d/jsc3d.touch.js"></script>
</HEAD>
<BODY>
<div style="width:800px; margin:auto; position:relative;">
<canvas id="cv" style="border: 1px solid;" width="750" height="400">
It seems you are using an outdated browser that does not support canvas :-(
</canvas>
<form action="">
<input type="checkbox" name="antagonist" value="1" onClick="this.value = -1*this.value; updateview(this.name,this.value);" checked> Antagonist</input>
<input type="checkbox" name="arch" value="1" onClick="this.value = -1*this.value; updateview(this.name,this.value);" checked> Main Arch</input>
<input type="checkbox" name="crown" value="1" onClick="this.value = -1*this.value; updateview(this.name,this.value);" checked> Crown</input>
</form>
</div>
<script type="text/javascript">
var canvas = document.getElementById('cv');
var viewer = new JSC3D.Viewer(canvas);
var components = ['models/dummy.stl', 'models/dummya.stl', 'models/dummyc.stl'];
var colors = [0xff0000, 0x0000ff, 0x00ff00, 0xffff00, 0x00ffff];
var theScene = new JSC3D.Scene;
var numOfLoaded = 0;
var onModelLoaded = function(scene) {
var meshes = scene.getChildren();
for (var i=0; i<meshes.length; i++) {
theScene.addChild(meshes[i]);
if (meshes.length > 0)
meshes[0].setMaterial(new JSC3D.Material('red-material', 0, colors[numOfLoaded]));
}
if (++numOfLoaded == components.length)
viewer.replaceScene(theScene);
};
for (var i=0; i<components.length; i++) {
var loader = new JSC3D.StlLoader;
loader.onload = onModelLoaded;
loader.loadFromUrl(components[i]);
}
viewer.setParameter('ModelColor', '#FF0000');
viewer.setParameter('BackgroundColor1', '#E5D7BA');
viewer.setParameter('BackgroundColor2', '#383840');
viewer.setParameter('RenderMode', 'flat');
viewer.setParameter('Renderer', 'webgl');
viewer.init();
viewer.update();
alert (meshes[1].visible.value);
//////////////////////////////////////////////////////////////////////////////////////
function updateview (name,value) {
var newScene = new JSC3D.Scene;
var newLoaded = 0;
var newModelLoaded = function(scene) {
var newMeshes = scene.getChildren();
for (var i=1; i<newMeshes.length; i++) {
newScene.addChild(newMeshes[i]);
if (newMeshes.length > 0)
newMeshes[0].setMaterial(new JSC3D.Material('red-material', 0, colors[newLoaded]));
}
if (++newLoaded == components.length)
viewer.replaceScene(newScene);
};
for (var i=1; i<components.length; i++) {
var newloader = new JSC3D.StlLoader;
newloader.onload = newModelLoaded;
newloader.loadFromUrl(components[i]);
}
viewer.update();
};
</script>
</BODY>
</HTML>
1) Add a <div> inside <body> tag say "objectlist".
<div id="objectlist"></div>
2) After the last viewer.update(); add this little code
viewer.onloadingcomplete = function() {
var shtml ="";
for(obj in viewer.scene.children) {
shtml+="<input type='checkbox' value='" + obj + "' checked onclick='setobject(this);'/>" + viewer.scene.children[object] + "<br />";
var objects = document.getElementById(objectlist);
objects.innerHTML = shtml;
};
3) Now add the setobject() function.
function setobject(self) {
viewer.scene.children[self.value].visible = self.checked;
}
Except point #1 everything should be in javascript code.
That's It...
Enjoy and in case any issues let me know # sarillaprasad#yahoo.com [or] post it here :D
I have been looking for a way to dynamically change the length of the input field in a HTML form.
I have come across the following:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example</title>
<script type="text/javascript">
window.onload = function() {
thelink = document.getElementById('MyLink');
linksize = thelink.value.length;
if (linksize < 10) thelink.size = 10;
if (linksize > 50) thelink.size = 50;
}
</script>
</head>
<body>
<input id="MyLink" type="text" value="http://www.domain.com/this/is/a/very/long/link/example" />
</body>
</html>
How would i adapt this to work for every input field on my very large form?
Thanks
For your case, I would give the required minimum and maximum as data-*= attributes,
For example:
<input id="MyLink" data-min="10" data-max="50" type="text" value="http://www.domain.com/this/is/a/very/long/link/example" />
Then iterate through the inputs in your form, drawing from the data attributes, and checking for the required length.
You can collect elements in a collection, either take them from the whole document or some its containing element. You can use e.g. getElementsByTagName('input');, getElementsByName('myInput'); or getElementsByClassName('shapable_input'); methods, if tags have set the corresponding attribute:
<input name="myInput" class="shapable_input" value="...." />
and then all collected tags can be tested in the loop:
window.onload = function() {
var links = document.getElementsByTagName('input');
//var linksc = links.getElementsByClassName('link');
var i, thelink, linksize;
for (i = 0; i < links.length; i++) {
thelink = links[i];
linksize = thelink.value.length;
if (linksize <= 10) {
thelink.size = 10;
}
if (linksize > 10) {
thelink.size = 50;
}
}
};
example