Jquery & HTML - dynamically create div-table - javascript

Say I have a textfield where the dimensions of the table are given. like 2 3
now I need to write a function that creates a table out of div-tags with those dimensions. The table has to be inserted in the <div id="output"> -element
I was thinking of making a string with osme for-loops that looks like this
<div>
<div> </div>
<div> </div>
</div>
<div>
... (more columns)
</div>
So that looks like a sequence of div-tags and afterwards I would convert this to html and insert it.
But isn't there a more efficient way?

In your Javascript,
<script type="text/javascript">
var rows,cols,str="";
function generateTable()
{
rows = documnt.getElementById('rows').value;
cols = documnt.getElementById('cols').value;
str ="<table>"
for(var i=0;i<rows;i++)
{
str = str+"<tr>";
for(vat j=0;j<cols;j++)
{
str = str+"<td></td>";
}
str =str+"</tr>";
}
str = str + "</table>;
documnt.getElementById('output').innerHTML = str;
}
</script>
In your HTML,
<input type="number" id="rows" placeholder="Number of rows" />
<input type="number" id="cols" placeholder="Number of cols" />
<input type="button" id="submit" value="Submit" onClick="generateTable();" />
<br>
<br>
<div id="output"></div>

Something like this maybe:
var rows = 3; //these would be populated by your text field entries
var columns = 2;
function makeTable() {
html = '<table>';
for(var i=0; i<rows; i++) {
html += '<tr>';
for(var j=0; j<columns; j++) {
html += '<td><p>Some Data</p></td>';
}
html += '</tr>';
}
html += '</table>';
document.getElementById("output").innerHTML = html;
}
table, td {
border: 1px solid black; padding: 5px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Table Maker</title>
</head>
<body>
<div id="output" onClick="makeTable()"><h1>Click me to make a table!</h1></div>
</body>
</html>

Related

Input to table in javascript

How can i add a content to html table with input fields.
For example here is html code:
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output");
output.innerHTML = "<tr><td>"+name+"</td><td>"+surname+"</td></tr>"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<title>Document</title>
<style>
table,td{
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="">
<div>
<label for="name">Name</label>
<input type="text" id="name">
</div>
<div>
<label for="name">Surname</label>
<input type="text" id="surname">
</div>
</form>
<input type="button" onclick="add();" value="Add">
<div>
<table id="output">
<thead><td>Name</td><td>Surname</td></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
I want to output my input fields in the table like rows.. but it does not work i dont know where is my problem i get [object HTMLInputElement].
And how can i make it work for entering more values because like this i can only enter one row
How about using this code?
It adds surname and name below the thead.
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.querySelector("#output tbody");
output.innerHTML += "<tr><td>"+name.value+"</td><td>"+surname.value+"</td></tr>"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<title>Document</title>
<style>
table,td{
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="">
<div>
<label for="name">Name</label>
<input type="text" id="name">
</div>
<div>
<label for="name">Surname</label>
<input type="text" id="surname">
</div>
</form>
<input type="button" onclick="add();" value="Add">
<div>
<table id="output">
<thead><td>Name</td><td>Surname</td></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
you should assign the value of the input fields like below.
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output");
output.innerHTML = "<tr><td>"+name.value+"</td><td>"+surname.value+"</td></tr>"
}
Try:
Give tbody an id to avoid removing thead
<tbody id="output2"></tbody>
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output2");
output.innerHTML = "<tr><td>" + name.value + "</td><td>" + surname.value + "</td></tr>";
}
You are trying to insert an HTML input element instead of the value of the element.
To make multiple entries possible try the last line of the function to:
output.innerHTML += "<tr><td>" + name.value + "</td><td>" + surname.value + "</td></tr>";

Trying to add background to <td> when clicked

A quick overview of what I'm trying to do: I created a function that takes user input of rows and columns and creates a grid. Then i want the user to pick a color and click on any pixel of the grid and apply the color. The table function works but my adding color function is not. Need a guide please
My Html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Pixel Art Maker!</title>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Monoton"
/>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<h1>Lab: Pixel Art Maker</h1>
<h2>Choose Grid Size</h2>
<form id="sizePicker">
Grid Height:
<input type="number" id="inputHeight" name="height" min="1" value="1" />
Grid Width:
<input type="number" id="inputWidth" name="width" min="1" value="1" />
<input type="submit" />
</form>
<h2>Pick A Color</h2>
<input type="color" id="colorPicker" />
<h2>Design Canvas</h2>
<table id="pixelCanvas"></table>
<script src="js/mine.js"></script>
</body>
</html>
my Javascript:
function makeGrid() {
let table = document.querySelector("#pixelCanvas");
let rows = document.querySelector("#inputHeight").value;
let cols = document.querySelector("#inputWidth").value;
let fulltable = "";
for (i = 0; i < rows; i++) {
fulltable += "<tr>";
for (y = 0; y < cols; y++) {
fulltable += "<td></td>";
}
fulltable += "</tr>";
}
table.innerHTML = fulltable;
return false;
}
function addColor() {
var cells = document.querySelectorAll("td");
cells.forEach((td) => {
td.onclick = () => {
let userColor = document.querySelector("#colorPicker").value;
this.style.backgroundColor = userColor;
};
});
}
document.addEventListener("DOMContentLoaded", () => {
addColor();
document.querySelector("#sizePicker").onsubmit = makeGrid;
});

how to have a set number of columns with jquery?

a bit new to jquery I have found this fiddle where I can edit and add both rows and columns I want the user to be able to only edit the number of rows only and have a set number of 4 columns?
https://jsbin.com/dehove/1/edit?html,css,js,console,output
HTML
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
Set Rows:<br>
<input type="text" id="setRows">
<br>
Set Columns:<br>
<input type="text" id="setColumns">
<button type='button'>Create Table</button>
<p id = "demo1"></p>
<p id = "demo2"></p>
</body>
</html>
jQuery
$(function(){ // DOM ready
$("button").click(function(){
var setRows = +$("#setRows").val();
var setColumns = +$("#setColumns").val();
var table = "<table>";
for (var i=0; i<setRows; i++){
table += "<tr>";
for (var j = 0; j < setColumns; j++) table += "<td>column</td>";
table += "</tr>";
}
table += "</table>";
$("p:last").after(table);
});
});
You need to change the value of setColumns to 4
var setColumns = 4;
Also delete the input for the columns
Your full HTML file looks like this
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
Set Rows:<br>
<input type="text" id="setRows">
<br>
<button type='button'>Create Table</button>
<p id = "demo1"></p>
<p id = "demo2"></p>
</body>
</html>
And This is the javascript
$(function(){ // DOM ready
$("button").click(function(){
var setRows = +$("#setRows").val();
var setColumns = 4;
var table = "<table>";
for (var i=0; i<setRows; i++){
table += "<tr>";
for (var j = 0; j < setColumns; j++) table += "<td>column</td>";
table += "</tr>";
}
table += "</table>";
$("p:last").after(table);
});
});
This is the js bin
Hope this helps :)

Why javascript not run line by line

Below are html/javascript code, but when call function calc(), its output a <ol>
tag first, but bot run script orderly.
I have remove the settimeout() function to make it running sync.
Can some one give explain will be appreciated.
function $(id) {
return document.getElementById(id);
}
regex_field = $('regx');
content = $('content');
output = $('output');
flag_field = $('flag')
flag_field.addEventListener('input', function() {
calc();
});
content.addEventListener('input', function() {
calc();
});
regex_field.addEventListener('input', function() {
calc();
});
function calc() {
//setTimeout(function () {
var re = new RegExp(regex_field.value, flag_field.value)
console.log(re);
found = content.value.match(re);
if (found) {
$('output').innerHTML = "<ol>";
for (let i = 0; i < found.length; i++) {
$('output').innerHTML += '<li>' + found[i] + '</li>';
}
$('output').innerHTML += "</ol>";
} else {
$('output').innerHTML = "Nothing Found!";
}
// }, 500);
}
<html>
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
</head>
<body>
<div class="row">
<div class="col-sm-6 form-inline">
RegExp
<input class="col-sm-4 form-control form-control-sm" type="text" id="regx" placeholder="Regex Input"> Flag
<input class="col-sm-1 form-control form-control-sm" type="text" id="flag">
<br>
<div>
<p>Input Content</p>
<textarea class="form-control col-sm-12" name="input" placeholder="Text" id="content" cols="30" rows="10"></textarea>
</div>
</div>
<div class="col-sm-6">
<p>Content get</p>
<div id="output"></div>
</div>
</div>
</body>
</html>
Output is like below. I don't understand why 'ol' tage go above the 'li' tag.
<div id="output">
<ol></ol> // <--- question here
<li>12</li>
<li>34</li>
</div>
When you do $('output').innerHTML = "<ol>"; it immediately adds the ol tag to #output. Since an <ol> without a closing </ol> is invalid, the DOM automatically closes it. So you get:
<div id="output">
<ol></ol>
</div>
Then, you do $('output').innerHTML += '<li>' + found[i] + '</li>';, so it adds that line to #output (which is also invalid, since an li can't belong to a div, but it doesn't know how to fix it):
<div id="output">
<ol></ol>
<li>12</li>
</div>
What you want to do it build up the innerHTML, then set it all at once, so more like:
if (found) {
var output = '';
output = "<ol>";
for (let i = 0; i < found.length; i++) {
output += '<li>' + found[i] + '</li>';
}
output += "</ol>";
} else {
output = "Nothing Found!";
}
$('output').innerHTML = output;

How to create a huge table of checkboxes (I mean HUGE!)

I am busy creating a website where a user has to select some checkboxes from a huge matrix of checkboxes. 100 by 100 = 10 000 boxes to be more specific!
The way I have set out doing this is by creating 100 vertical divs, each with 100 checkboxes in them.
This seems to work OK but it ends up being a HUGE amount of code! So much, that when I hit refresh in Dream Weaver, it crashes!
I'm pretty new at HTML and Javascript. Is there a better way of doing this??
I included a very small basic example of what I have done
<html lang="en"><head><meta name="generator" content="PSPad editor, www.pspad.com">
<title>Checkbox No Vertical Space</title>
<style type="text/css">
#aDiv,
#bDiv,
#cDiv{
float:left;
width:12px;
}
#aDiv input,
#bDiv input,
#cDiv input{
clear:left;
float:left;
margin:0;
padding:0;
width:12px;
height:12px;
}
</style></head><body>
<div id="aDiv">
<input type="checkbox" value="a1">
<input type="checkbox" value="a2">
<input type="checkbox" value="a3">
<input type="checkbox" value="a4">
<input type="checkbox" value="a5">
<input type="checkbox" value="a6">
</div>
<div id="bDiv">
<input type="checkbox" value="b1">
<input type="checkbox" value="b2">
<input type="checkbox" value="b3">
<input type="checkbox" value="b4">
<input type="checkbox" value="b5">
<input type="checkbox" value="b6">
</div>
<div id="cDiv">
<input type="checkbox" value="c1">
<input type="checkbox" value="c2">
<input type="checkbox" value="c3">
<input type="checkbox" value="c4">
<input type="checkbox" value="c5">
<input type="checkbox" value="a6">
</div>
</body></html>
Thanks!
Allan
This code performs well:
var i, j, div, cb, frag;
frag = document.createDocumentFragment();
cb = document.createElement( 'input' );
cb.type = 'checkbox';
for ( i = 0; i < 100; i += 1 ) {
div = document.createElement( 'div' );
for ( j = 0; j < 100; j += 1 ) {
div.appendChild( cb.cloneNode( false ) );
}
frag.appendChild( div );
}
document.body.appendChild( frag );
Live demo: http://jsfiddle.net/Kyswa/1/show/
(although my machine has performance issues when scrolling the page)
I went ahead and made a jQuery version of this, and made sure the width was dynamically calculated to ensure that you have 100x100 checkboxes cross browser. I also added some html5 data attributes to the checkboxes, so you wont have to calculate it every time. Also, there's a single event hooked up to a containing div, so events will perform well. Here's the code:
HTML
<div id="checkboxes">
</div>​
CSS
#checkboxes {
line-height: 0;
}
#checkboxes input[type="checkbox"] {
margin: 0px;
padding: 0px;
}​
JavaScript + jQuery 1.7
$(function(){
var target = $('#checkboxes');
var x, y, checkbox;
for(x = 0; x < 100; x++)
{
for(y = 0; y < 100; y++)
{
checkbox = $('<input></input>', {
'type': 'checkbox',
'data-x': x,
'data-y': y
});
target.append(checkbox);
}
}
target.width(checkbox.outerWidth() * 100);
target.on('change', 'input:checkbox', function(){
var $this = $(this),
x = $this.data('x'),
y = $this.data('y'),
checked = $this.prop('checked');
alert('checkbox changed (' + x + ', ' + y + '): ' + checked);
});
});​
Example
http://jsfiddle.net/xixonia/Uq7CU/1/
Here's a fun version where you can draw by moving your mouse over the checkboxes:
http://jsfiddle.net/xixonia/Uq7CU/2/
This may not be proper HTML or follow recommended guidelines, but you could use a <table></table>. Get rid of your <div></div>'s, make one <div></div> with an id of "grid", and add this to your javascript:
var grid = "";
grid += "<table>";
for (var row = 0; row < 100; row++)
{
grid += "<tr>";
for (var col = 0; col < 100; col++)
{
grid += "<td>";
grid += "<input type='checkbox' value='" + row + "-" + col + "'>";
grid += "</td>";
}
grid += "</tr>";
}
grid += "</table>";
document.getElementById("grid").innerHTML = grid;
Please let me know if this doesn't work or if it has any errors!
Do you have to have checkboxes?
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Small Page</title>
<style>
table{layout:fixed;width:95%;margin:0 auto;}
td{border:ridge thin gray;width:1%;font-size:8px;color:white;background-color:white;padding:0}
td:hover{background-color:blue}
input{font-size:smaller}
</style>
</head>
<body>
<h1>Boxes<br>
<input type="text" size="20" value=""></h1>
<script>
onload= function(){
document.getElementsByTagName('table')[0].onclick= function(e){
e= e || window.event;
var r= 0, c= 0, row, col,
who= e.target || e.srcElement,
msg= document.getElementsByTagName('input')[0];
if(who.tagName== 'TD'){
who.style.backgroundColor= 'red';
msg.value= who.id.replace('r','row: ').replace('c',' col: ');
}
}
}
var r= 1, c= 1, str= '<table cellspacing="0" cellpadding="0">\n<tbody>';
while(r<101){
str+= '\n<tr>';
c= 1;
while(c<101){
str+= '<td id="r'+r+'c'+c+'">x</td>';
++c;
}
str+= '</tr>';
++r;
}
str+='</tbody>\n</table>\n';
document.write(str);
</script>
<br>
</body>
</html>

Categories