Creating nested tables - javascript

Good day. I'm trying to create nested tables one hundred times. However, my code creates one main table and then inside that, there are 100 separate tables. (Thanks to Sir Sachin for the help) What I need is table within a table. Please help me fix the code.
<html>
<head> <title> Hello! </title>
<script type="text/javascript">
function add() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value=1 id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
ni.appendChild(newdiv);
for(var i=1;i<100;i++) {
var ni = document.getElementById(divIdName);
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
var j=i++;
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value='" + j + "' id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
ni.appendChild(newdiv);
}
}
</script>
</head>
<body onload="add()">
<table border="1">
<tr>
<td> Hello! <input type='hidden' value='0' id='theValue' />
<div id='myDiv'> </div> </td>
</tr>
</table>
</body>
</html>

This should do it (I have removed the hidden input as it is not needed): http://jsfiddle.net/rPR9w/1/
function add() {
for (i=1; i<=100; i++) {
addAnother(i);
}
}
function addAnother(counter) {
var container = document.getElementById('myDiv' + counter);
container.innerHTML = makeTable(counter + 1);
}
function makeTable(counter) {
return "<table border=1><tr><td> Hello! <div id='myDiv" + counter + "'></td></tr></table>";
}

Related

I am developing duolingo type sentence practice in javascript. I have implemented it but it needs more improvement

I have used following code to develop sentence grammar practice. When I click button then order should to maintained. I want it when button clicked then it should hide but after click on top button again show up.
Move sentence to left if there is blank. Also show button again if words clicked again.
Should using only buttons for showing at top also at bottom?
<html>
<head>
<title>
</title>
</head>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<div id="val"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
for(i=0;i<senArr.length;i++)
{
//alert(senArr[i]);
dashElement += "<div onclick='funDiv(this.id);' style='display: inline'" + "id = dashid" + i + ">" + '__ ' + '</div>';
}
var dash = document.getElementById("dash");
dash.innerHTML = dashElement;
//var dashID = document.getElementById("dashid0").innerHTML;
//var dash1 = document.getElementById("val");
//dash1.innerHTML= dashID;
var htmlElements = "";
for (var i = 0; i < senArr.length; i++) {
htmlElements += "<button onclick='fun(this.id);' id = 'btn" + i + "'>" + senArr[i] + '</button>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
var ii = 0;
function funDiv(clicked){
//alert(clicked);
var inText = document.getElementById(clicked).innerHTML;
document.getElementById(clicked).innerHTML = " __ " ;
ii--;
}
function fun(clicked){
//alert(clicked);
document.getElementById(clicked).style.display = "none";
document.getElementById("dashid" + ii).innerHTML = document.getElementById(clicked).innerHTML + " ";
//document.getElementById(clicked).remove();
ii++;
}
</script>
</script>
</body>
</html>
How about something like this?
<html>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<div id="val"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
for (var i = 0; i < senArr.length; i++) {
dashElement += `<div onclick='dashClick(this.id);' style='display: inline' id=dash${i}> __ </div>`;
}
var dash = document.getElementById("dash");
dash.innerHTML = dashElement;
var htmlElements = "";
for (var i = 0; i < senArr.length; i++) {
htmlElements += "<button onclick='btnClick(this.id);' id = 'btn" + i + "'>" + senArr[i] + '</button>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
var picked = 0;
function dashClick(clicked) {
const dash = document.getElementById(clicked);
dash.innerHTML = " __ ";
const btn = document.getElementById(`btn${dash.btnId}`);
btn.style.display = "inline";
picked--;
}
function btnClick(clicked) {
var btnId = clicked.replace('btn', '');
document.getElementById(clicked).style.display = "none";
const dash = document.getElementById("dash" + picked)
dash.innerHTML = document.getElementById(clicked).innerHTML + " ";
dash.btnId = btnId;
picked++;
}
</script>
</body>
</html>
I have implemented it using appendChild and remove functions of JavaScript.
<html>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
var btnElements = "";
for (var i = 0; i < senArr.length; i++) {
btnElements += "<button onclick='btnClick(this.id);' id = 'btn" + i + "'> " + senArr[i] + ' </button>';
}
var container = document.getElementById("container");
container.innerHTML = btnElements;
var picked = 0;
function dashClick(clicked) {
//console.log(clicked);
var buttons = document.getElementsByTagName('button');
var dash = document.getElementById("dash");
dashChild = dash.childNodes;
console.log(document.getElementById(clicked).innerText);
for(i=0;i<senArr.length;i++){
if(document.getElementById(clicked).innerText.trim() == buttons[i].innerText.trim()){
//console.log("Match");
buttons[i].style.opacity = "1";
buttons[i].style.pointerEvents = "auto";
}
}
document.getElementById(clicked).remove(); // remove clicked text
}
// Button click
function btnClick(clicked) {
var dashElement = document.createElement("div");
var text = document.getElementById(clicked).innerText;
dashElement.style.display = "inline";
dashElement.innerHTML = "<div style='display: inline' onclick='dashClick(this.id);' id=" + picked +"> " + text + " </div>"; // add text at top of button
document.getElementById("dash").appendChild(dashElement);
picked++;
document.getElementById(clicked).style.opacity = "0"; //hide button that has been clicked
document.getElementById(clicked).style.pointerEvents = "none";
}
</script>
</body>
</html>

Looping through text boxes, using id as a variable?

Basically I'm trying to populate an array with some values in text boxes. I thought I could do it by incrementing though ids, but it isn't working.
Here it is:
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>
Is it possible doing it my method, or will it inevitably not work for whatever reason? Doing some searches it seems jquery might be the way to go, but I'm not sure how to get started with that.
jQuery certainly simplifies things, but it can't do anything that JavaScript can't do, and many amazing websites were built long before jQuery came into existence.
In populateArray(), remove innerHTML here:
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
Should be:
mod[i] = parseInt(document.getElementById(pop).value);
You can simplify the function like this:
function populateArray() {
var i;
for(i = 0 ; i < sections * 3 ; i++) {
mod[i] = parseInt(document.getElementById(i).value);
}
document.getElementById('debug').innerHTML = mod.toString();
}
In addSection(), this wipes out the values of existing input elements:
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
Instead, you should create new input elements and append them.
Here's a rewrite of the function:
var input= document.getElementById('input');
function addSection(){
var inp, i;
sections++;
for(var i = 0 ; i < 3 ; i++) {
inp= document.createElement('input');
inp.type= 'text';
inp.id= identifier++;
input.appendChild(inp);
}
input.appendChild(document.createElement('br'));
} //addSection
In removeSection(), values of all input elements are wiped out.
Instead of rewriting that function, I've done a complete rewrite or your program, without any global variables and without assigning IDs to the input elements.
If you have any questions, I'll update my answer with explanations.
Snippet
function addSection() {
var input= document.getElementById('input'),
sect= document.querySelector('section');
input.appendChild(sect.cloneNode(true));
}
function removeSection() {
var input= document.getElementById('input'),
sects= document.querySelectorAll('section');
if(sects.length > 1) {
input.removeChild(sects[sects.length-1]);
}
}
function calculate() {
var inp= document.querySelectorAll('section input'),
debug= document.getElementById('debug'),
mod= [],
i,
val;
for(i = 3 ; i < inp.length ; i++) {
val= parseInt(inp[i].value);
mod.push(val || 0);
}
debug.innerHTML = mod.toString();
}
section:first-of-type {
display: none;
}
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'>
<section>
<input type="text">
<input type="text">
<input type="text">
</section>
</div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
This version of your script stores the actual elements in an array of sections. That way you can loop through them as you would an array, and alter the contents that way.
Here's a pen of the code: looping through added elements
var sections = [];
var output = document.getElementById('input');
function addSection(){
var section = document.createElement('div');
for (var i = 0; i < 3; i++) {
el = document.createElement('input');
el.type = 'text';
section.appendChild(el);
}
sections.push(section);
output.appendChild(section);
}
function removeSection(){
if (sections.length > 0){
output.removeChild(sections.pop())
}
}
function calculate(){
populateArray();
}
function populateArray(){
for (var i = 0; i < sections.length; i++) {
for (var j = 0; j < sections[i].children.length; j++ ) {
sections[i].children[j].value = (i+1) * (j+2);
}
}
}
If your problem is the NaN, this is because you select an input field and then first try to read its innerHtml before reading its value. Read values of inputs directly.
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>

Increment textarea name to javascript function

So what I am trying to achieve is to increment the points".$id." in the javascript code below starting from 0 like points+n and it would be a dynamic value according to rows in a table. Same for the value 'button".$id."' and all this is because of styled radiobutton labels that are looped etc.
So all I want to do is get rid of all the hardcoded different var txt1 to txt+n, button0 to button+n and points0 to points+n in the JavaScript function.
The real problem here for me is the line: var buttons1 = document.forms[0].button0; how to replace the 0 in button0 to the 'i' in a for loop. Someting like button + i won't work.
Oh and what I'm trying to do is get the values from the radiobuttons to a textarea with one buttongroup and textarea per tablerow.
The code below works for the first 7 rows in my table...
echo "
<td>
<div class='radio'>
<input id='".$temp1."' type='radio' name='button".$id."' onclick='myFunction()' value='4'>
<label for='".$temp1."'></label>
<input id='".$temp2."' type='radio' name='button".$id."' onclick='myFunction()' value='3'>
<label for='".$temp2."'></label>
<input id='".$temp3."' type='radio' name='button".$id."' onclick='myFunction()' value='2'>
<label for='".$temp3."'></label>
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction()' value='1'>
<label for='".$temp4."'></label>
</div>";
echo"<textarea id='points".$id."' name='points".$id."' cols='1' rows='1' ;> </textarea>
</td>
</tr>";
The Javascript function:
function myFunction() {
var txt1 ='';
var txt2 ='';
var txt3 ='';
var txt4 ='';
var txt5 ='';
var txt6 ='';
var txt7 ='';
var buttons1 = document.forms[0].button0;
var buttons2 = document.forms[0].button1;
var buttons3 = document.forms[0].button2;
var buttons4 = document.forms[0].button3;
var buttons5 = document.forms[0].button4;
var buttons6 = document.forms[0].button5;
var buttons7 = document.forms[0].button6;
var buttons8 = document.forms[0].button7;
for (var i = 0; i < 4; i++) {
if (buttons1[i].checked) {
txt1 = txt1 + buttons1[i].value + " ";
}
if (buttons2[i].checked) {
txt2 = txt2 + buttons2[i].value + " ";
}
if (buttons3[i].checked) {
txt3 = txt3 + buttons3[i].value + " ";
}
if (buttons4[i].checked) {
txt4 = txt4 + buttons4[i].value + " ";
}
if (buttons5[i].checked) {
txt5 = txt5 + buttons5[i].value + " ";
}
if (buttons6[i].checked) {
txt6 = txt6 + buttons6[i].value + " ";
}
if (buttons7[i].checked) {
txt7 = txt7 + buttons7[i].value + " ";
}
}
document.getElementById("points0").value = txt1;
console.log(txt1);
document.getElementById("points1").value = txt2;
console.log(txt2);
document.getElementById("points2").value = txt3;
console.log(txt3);
document.getElementById("points3").value = txt4;
console.log(txt4);
document.getElementById("points4").value = txt5;
console.log(txt5);
document.getElementById("points5").value = txt6;
console.log(txt6);
document.getElementById("points6").value = txt7;
console.log(txt7);
}
i think what you need is use the "eval" function in javascript
try the following
var buttons1;
var buttons2;
var buttons3;
var buttons4;
var buttons5;
var buttons6;
var buttons7;
var buttons8;
var j;
for(var i=0;i<8;i++){
j=i+1;
eval("buttons" +j+ " = document.forms[0].button" +i+ ";");
}
If i understood correctly,
Try something like this:
change your onclick as following:
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction(this)' value='1'>
and change function :
function myFunction(button){
var name= button.name;
var id= name.split('button')[1];;
document.getElementById("points"+id).value = buttons.value +" ";
}

How to read value of Textbox which is inside table

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>

Im trying to build a basic math game using javascript

This is all my code I hope you can see where I'm going wrong.
var $randomnumber1;
var $randomnumber2;
var $answer;
var $counter = 1;
var $data;
function start_game() {
document.getElementById('counternumber').innerHTML = $counter;
document.getElementById('txtbox').value = "";
$randomnumber1 = Math.floor(Math.random()*11);
document.getElementById('num1').innerHTML = $randomnumber1;
$answer = $randomnumber1 + $randomnumber2;
$counter++;
setFocus();
}
function check_answer() {
var $txt = document.getElementById('txtbox');
var $value = $txt.value;
if ($value == $answer) {
alert('You are correct');
}
else {
alert('You are incorrect, the answer was ' + $answer);
}
document.getElementById('txtbox').value = "";
document.getElementById('num1').innerHTML = "";
document.getElementById('num2').innerHTML = "";
$randomnumber1 = Math.floor(Math.random()*11);
$randomnumber2 = Math.floor(Math.random()*11);
document.getElementById('num1').innerHTML = $randomnumber1;
document.getElementById('num2').innerHTML = $randomnumber2;
$answer = $randomnumber1 + $randomnumber2;
document.getElementById('counternumber').innerHTML = $counter;
$counter++;
if ($counter > 4) {
alert ('End of game......Thanks for playing');
$counter = 1;
document.getElementById('num1').innerHTML = "";
document.getElementById('num2').innerHTML = "";
}
function addAnswers() {
var data = $randomnumber1 + " + " + $randomnumber2 + " = " + ($randomnumber1+$randomnumber2)
var newListItem = document.createElement('li');
var newText = document.createTextNode(data);
newListItem.appendChild(newText);
document.getElementById("ans").appendChild(newListItem);
}
<div class="container" id="wrapper">
<h3>Games Played = <b id='counternumber'></b> / 3 </h3>
<div id="total">Total: <p id="sumtotal"></p></div>
<div class="left"><h3 id="num1"></h3></div>
<div class="plus"><img src="images/plus.png"></div>
<div class="right"><h3 id="num2"></h3></div>
<button onclick="start_game(); myCountDown()">Start Game</button>
<form id="form">
<input type="text" id="txtbox" />
<input type="button" value="Answer" onclick="check_answer(); setFocus(); ShowResults(); sumResults()" />
</form>
</div>
home page
</div> <!-- /content -->
<div id="aside">
</div>
You could use this:
function addAnswers()
{
var data = $randomnumber1 + " + " + $randomnumber2 + " = " + ($randomnumber1+$randomnumber2)
var newListItem = document.createElement('li');
var newText = document.createTextNode(data);
newListItem.appendChild(newText);
document.getElementById("ans").appendChild(newListItem);
}
Your question is unclear, but this should be something along the lines of what you're looking for. What you have to do is add a <ul> with the id of ans and this function will append li components to it (your answers) every time you run it. The answer itself will be stored into data.
Try it - if you want help customizing it, please update your answer.

Categories

Resources