How to filling table cells with random numbers through button in JavaScript - javascript

[User may enter number of rows and columns, then chess board appears after clicking enter button.][The problem is I cannot fill the table cells with random numbers using Fill button]
So far the code of JavaScript is
var a, b, tableElem, rowElem, colElem;
function createTable() {
a = document.getElementById('row').value;
b = document.getElementById('column').value;
if (a == "" || b == "") {
alert("Enter a number");
} else {
tableElem = document.createElement('table');
for (var i = 0; i < a; i++) {
rowElem = document.createElement('tr');
for (var j = 0; j < b; j++) {
colElem = document.createElement('td');
rowElem.appendChild(colElem);
if (i % 2 == j % 2) {
colElem.className = "white";
} else {
colElem.className = "black";
}
}
tableElem.appendChild(rowElem);
}
document.body.appendChild(tableElem);
}
}
and Html is
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="row" placeholder="Row">
</div>
<div class="form-group">
<input type="text" class="form-control" id="column" placeholder="Column">
</div>
<button type="button" class="btn btn-primary" onclick="createTable()">
Enter
</button>
<button onclick="fillTable()" id="btn" type="button" class="btn btn-info">
Fill
I used jQuery
$(document).ready(function () {
$('#btn').click(function () {
$(colElem).append(1);
});
});
but with this code only bottom right corner is filled. Please can you give info how to fill all cells of the table with random number via Fill button

$(colElem) selector pointing to the last cell of the table... you need to select each and every cell and assign the random number... look into the below code (it will add random number between 0 to 99) to solve the issue... remove onclick="fillTable()" from the button..
$('#btn').click(function () {
$(tableElem).find("td").each(function(){
$(this).html(Math.floor(Math.random() * 100));
});
});

Related

Deleting a table row using row numbers in Javascript

I created a table that can add rows by filling in a form. Every row added to the table, get's a row number. Now I want to delete a certain row by putting in the row number in another input (using a deleteRow-function).
<table id="table">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
</table>
<form action="" id="form" name="form">
First name: <input type="text" id="fnaam"> <br>
Last name: <input type="text" id="lnaam"><br>
Points: <input type="text" id="points">
</form>
<button type="button" id="addBtn">Voeg toe</button>
Fill in row number: <input type="text" id="deleteRowInput"> <br>
<button type="button" id="deleteBtn">Delete Row</button>
This is the Javascript I use. I created a deleteRow-function, but it's not working yet. Thanks!
var addBtn = document.getElementById('addBtn');
var deleteBtn = document.getElementById('deleteBtn');
addBtn.onclick = addRow;
deleteBtn.onclick = deleteRow;
var rowNumber = 0;
function addRow() {
//getting data from form
var form = document.getElementById('form');
var newData = [];
for(var i = 0; i < form.length; i++) {
newData[i] = form.elements[i].value;
}
if(validateForm() == true) {
rowNumber++;
//Put data in table
var table = document.getElementById('table');
var newRow = table.insertRow();
//Adding rownumber to row
newRow.innerHTML = `<tr><td><i>${rowNumber}</i></td><tr>`;
for(var i = 0; i < 3; i++) {
var newCell = newRow.insertCell(i);
newCell.innerHTML = newData[i];
}
}
form.reset();
}
function deleteRow() {
var table = document.getElementById('table');
var input = document.getElementById('deleteRowInput');
}
//validating form
function validateForm() {
var f = document.getElementById('form');
if(f.fnaam.value == '') {
alert('Please fill in first name!');
return false;
}
if(f.lnaam.value == '') {
alert('Please fill in last name!');
return false;
}
if(f.points.value == '') {
alert('Please fill in points!');
return false;
}
if(isNaN(f.points.value)) {
alert('Points should be a number!')
return false
}
return true;
}
To simplify matters, add a data- attribute to the tr elements containing the respective row number.
Modification in addNumber:
newRow.innerHTML = `<tr data-row-number="${rowNumber}"><td><i>${rowNumber}</i></td><tr>`;
The deleteRow function could look like this:
function deleteRow() {
let table = document.getElementById('table');
let input = document.getElementById('deleteRowInput');
let n_rowToDelete = input.value;
document.querySelector ( 'tr[data-row-number="' + n_rowToDelete + '"]' ).remove();
}
Watch out for:
having 1 table only.
not to delete the last row
... and be aware that after the first call to deleteRow there will neither be a contiguous list of row numbers nor will the row number mirror the position of the row in the sequence of table rows.

How to Check Password validation dynamically using jquery/javascript?

Kindly read my question fully before assign my one as duplicate.
Hi I tried to verify password dynamically during keypress. Actually it is working for me while enter the password. But When I delete the password only 2 conditions satisfies. My code and images below:
My password box html code is
<div class="form-group has-feedback">
<input class="form-control" id="NewPassword" placeholder="New Password" onkeypress="EnterPassword()" onkeydown="DeletePassword()" type="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
I used glyphicon-remove infront of each conditions for the password. When I enter the password each icon change to glyphicon-ok if the condition satisfies.
These are my password conditions with icon:
Lets assume my password as Password#123, it contains all my required things, so all the icons changed to ok.
But when I delete the password only 2 of the conditions satisfied.
Codes for the function below:
<script type="text/javascript" >
function EnterPassword() {
$("#NewPassword").keyup(function () {
var regex1 = new Array();
var regex2 = new Array();
var regex3 = new Array();
var regex4 = new Array();
regex1.push("[A-Z]"); //Uppercase Alphabet.
regex2.push("[a-z]"); //Lowercase Alphabet.
regex3.push("[0-9]"); //Digit.
regex4.push("[!###$%^&*]"); //Special Character.
if ($(this).val().length>6) {
$("#Length").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
for (var i = 0; i < regex1.length; i++) {
if (new RegExp(regex1[i]).test($(this).val())) {
$("#UpperCase").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
for (var i = 0; i < regex2.length; i++) {
if (new RegExp(regex2[i]).test($(this).val())) {
$("#LowerCase").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
for (var i = 0; i < regex3.length; i++) {
if (new RegExp(regex3[i]).test($(this).val())) {
$("#Numbers").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
for (var i = 0; i < regex4.length; i++) {
if (new RegExp(regex4[i]).test($(this).val())) {
$("#Symbols").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
});
}
function DeletePassword() {
$("#NewPassword").keyup(function () {
var regex1 = new Array();
var regex2 = new Array();
var regex3 = new Array();
var regex4 = new Array();
regex1.push("[A-Z]"); //Uppercase Alphabet.
regex2.push("[a-z]"); //Lowercase Alphabet.
regex3.push("[0-9]"); //Digit.
regex4.push("[!###$%^&*]"); //Special Character.
var thisVal =$(this).val();
if ($(this).val().length<6) {
$("#Length").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
for (var i = 0; i < regex1.length; i++) {
if (new RegExp(regex1[i]).test(!thisVal)) {
$("#UpperCase").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
for (var i = 0; i < regex2.length; i++) {
if (new RegExp(regex2[i]).test(!thisVal)) {
$("#LowerCase").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
for (var i = 0; i < regex3.length; i++) {
if (new RegExp(regex3[i]).test(!thisVal)) {
$("#Numbers").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
for (var i = 0; i < regex4.length; i++) {
if (new RegExp(regex4[i]).test(!thisVal)) {
$("#Symbols").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
});
}
</script>
NOTE: UpperCase,LowerCase,Numbers,Symbols are the Id name that I gave to the tag where I used the glyphicon remove icon.
If my codes not working completely means my question may comes under duplicate. But Its Partially working, So kindly let me know if there is any mistake I did on my code.
Thanks in Advance
We can simplify your code a lot.
For a start instead of using inline event handlers we will use jQuery's .on to bind the event.
Next we'll consolidate your rules into a JSON object array with the rules target.
We then iterate the Regex based rules adding and removing classes as required
/*Actual validation function*/
function ValidatePassword() {
/*Array of rules and the information target*/
var rules = [{
Pattern: "[A-Z]",
Target: "UpperCase"
},
{
Pattern: "[a-z]",
Target: "LowerCase"
},
{
Pattern: "[0-9]",
Target: "Numbers"
},
{
Pattern: "[!###$%^&*]",
Target: "Symbols"
}
];
//Just grab the password once
var password = $(this).val();
/*Length Check, add and remove class could be chained*/
/*I've left them seperate here so you can see what is going on */
/*Note the Ternary operators ? : to select the classes*/
$("#Length").removeClass(password.length > 6 ? "glyphicon-remove" : "glyphicon-ok");
$("#Length").addClass(password.length > 6 ? "glyphicon-ok" : "glyphicon-remove");
/*Iterate our remaining rules. The logic is the same as for Length*/
for (var i = 0; i < rules.length; i++) {
$("#" + rules[i].Target).removeClass(new RegExp(rules[i].Pattern).test(password) ? "glyphicon-remove" : "glyphicon-ok");
$("#" + rules[i].Target).addClass(new RegExp(rules[i].Pattern).test(password) ? "glyphicon-ok" : "glyphicon-remove");
}
}
/*Bind our event to key up for the field. It doesn't matter if it's delete or not*/
$(document).ready(function() {
$("#NewPassword").on('keyup', ValidatePassword)
});
.glyphicon-remove {
color: red;
}
.glyphicon-ok {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group has-feedback">
<input class="form-control" id="NewPassword" placeholder="New Password" type="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div id="Length" class="glyphicon glyphicon-remove">Must be at least 7 charcters</div>
<div id="UpperCase" class="glyphicon glyphicon-remove">Must have atleast 1 upper case character</div>
<div id="LowerCase" class="glyphicon glyphicon-remove">Must have atleast 1 lower case character</div>
<div id="Numbers" class="glyphicon glyphicon-remove">Must have atleast 1 numeric character</div>
<div id="Symbols" class="glyphicon glyphicon-remove">Must have atleast 1 special character</div>
i give you simple example.
Html
<!DOCTYPE HTML>
<html>
<head>
<title>Password strength checker in jQuery</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><!-- jQuery Library-->
<link rel="stylesheet" href="css/passwordscheck.css" /><!-- Include Your CSS file here-->
<script src="js/passwordscheck.js"></script><!-- Include Your jQUery file here-->
</head>
<body>
<div id="container">
<div id="header">
<h2>Password Strength Checking with jQuery</h2>
<hr>
</div>
<div id="content">
<form id="register">
<label for="password"><b>Password : </b></label>
<input name="password" id="password" type="password" placeholder="Type Your Password here"/>
<span id="result"></span>
</form>
</div>
</div>
</body>
</html>
JS
$(document).ready(function() {
$('#password').keyup(function() {
$('#result').html(checkStrength($('#password').val()))
})
function checkStrength(password) {
var strength = 0
if (password.length < 6) {
$('#result').removeClass()
$('#result').addClass('short')
return 'Too short'
}
if (password.length > 7) strength += 1
// If password contains both lower and uppercase characters, increase strength value.
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
// If it has numbers and characters, increase strength value.
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1
// If it has one special character, increase strength value.
if (password.match(/([!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// If it has two special characters, increase strength value.
if (password.match(/(.*[!,%,&,#,#,$,^,*,?,_,~].*[!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// Calculated strength value, we can return messages
// If value is less than 2
if (strength < 2) {
$('#result').removeClass()
$('#result').addClass('weak')
return 'Weak'
} else if (strength == 2) {
$('#result').removeClass()
$('#result').addClass('good')
return 'Good'
} else {
$('#result').removeClass()
$('#result').addClass('strong')
return 'Strong'
}
}
});
Reference : Link
one of the best example for you
i hope you understand.

How to limit the amount of times an element can be created

Is there a way to limit the amount of times a user can click a button to create an element? This is what I have managed to put together so far. Thank you.
JavaScript
var ClickCount = 0;
function countClicks() {
var clickLimit = 8 ; //Max number of clicks
if(ClickCount<=clickLimit) {
populateTipItem();
}
else if(ClickCount > clickLimit)
{
return;
}
}
// TIP LIST
function populateTipItem() {
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("class", "form-control mt-1 tip-item");
x.setAttribute("placeholder", "Another Tip Item! ... 250tks");
document.getElementById("tipList").appendChild(x);
}
HTML
<div id="tipList" class="form-group mt-5">
<label for="tips">Your Tip Menu Items</label>
<small class="form-text text-muted">Max 10 items.</small>
<input type="text" name="tips" class="form-control mt-1 tip-item" placeholder="Tip Item! ... 10tks"/>
</div>
<button class="btn btn-secondary" onclick="return countClicks()">Add Tip Item</button>
You're almost completed. The main change is to add ClickCount++ so you'll know how much elements were created.
var ClickCount = 0;
var clickLimit = 8 ; //Max number of clicks
function countClicks() {
if(ClickCount<=clickLimit) {
ClickCount++;
populateTipItem();
}
else if(ClickCount > clickLimit) {
return;
}
}
alternatively you can count the number of elements created:
var clickLimit = 8;
var tipList = document.getElementById('tipList');
function countClicks() {
if (tipsList.children.length < clickLimit) {
populateTipItem();
}
}

How to show nearest div id for a given input number?

Let's say I have the following input field:
<input id="inputField" type="number" value="">
and some divs such as:
<div id="1000"></div>
<div id="1200"></div>
<div id="1500"></div>
<div id="1900"></div>
...
When the user enters a number in the input field, I want my code to go to the nearest div id to that number.
e.g: If user enters 1300 then show div with id = "1200".
What's the most efficient way to implement that in javascript considering there will be a large number of divs?
Right now I'm doing:
<script>
function myFunction()
{
var x = document.getElementById("inputField").value;
if(x >= 1750 && x <= 1900)
{
window.location.hash = '#1800';
}
}
</script>
One way is to wrap all your divs with number ids in another div if you can (and give it some id, say 'numbers'); this allows you to find all the divs in your javascript file.
Javascript:
// Get all the divs with numbers, if they are children of div, id="numbers"
let children = document.getElementById('numbers').children;
let array = [];
for (i = 0; i < children.length; i++) {
// Append the integer of the id of every child to an array
array.push(parseInt(children[i].id));
}
// However you are getting your input number goes here
let number = 1300 // Replace
currentNumber = array[0]
for (const value of array){
if (Math.abs(number - value) < Math.abs(number - currentNumber)){
currentNumber = value;
}
}
// You say you want your code to go to the nearest div,
// I don't know what you mean by go to, but here is the div of the closest number
let target = document.getElementById(currentNumber.toString());
Let me know if there's more I can add to help.
Demo
function closestNum() {
let children = document.getElementById('numbers').children;
let array = [];
for (i = 0; i < children.length; i++) {
array.push(parseInt(children[i].id));
}
let number = document.getElementById('inputnum').value;
currentNumber = array[0]
for (const value of array) {
if (Math.abs(number - value) < Math.abs(number - currentNumber)) {
currentNumber = value;
}
}
let target = document.getElementById(currentNumber.toString());
document.getElementById('target').innerHTML = target.innerHTML;
}
<div id="numbers">
<div id="1000">1000</div>
<div id="2000">2000</div>
<div id="3000">3000</div>
<div id="4000">4000</div>
<div id="5000">5000</div>
</div>
<br />
<input type="text" id="inputnum" placeholder="Input Number" onchange="closestNum()" />
<br />
<br /> Target:
<div id="target"></div>
With some optimization this shall be ok-
var element;
document.addEventListener("change",
function(evt){
if(element && element.classList){
element.classList.remove("selected", false);
element.classList.add("unselected", true);
}
var listOfDivs =
document.querySelectorAll(".unselected");
var val = evt.target.value;
var leastAbs=listOfDivs[0].id;
for(let anIndex=0, len=listOfDivs.length;anIndex<len;anIndex++){
if(Math.abs(listOfDivs[anIndex].id-val)<leastAbs){
leastAbs = Math.abs(listOfDivs[anIndex].id-val);
element = listOfDivs[anIndex];
}
}
element.classList.remove("unselected");
element.classList.add("selected");
});
.selected{
background-color:red;
}
.unselected{
background-color:yellow;
}
.unselected, .selected{
width:100%;
height:50px;
}
<input id="inputField" type="number" value="">
<div id="1000" class='unselected'>1</div>
<div id="1200" class='unselected'>2</div>
<div id="1500" class='unselected'>3</div>
<div id="1900" class='unselected'>4</div>
This may work for you. Loops through each div and compared it to your inputted ID. Tracks closest one, hides all divs, then displays the closest.
document.getElementById("inputField").addEventListener("change", function(){
var divs = document.getElementsByTagName("div");
var closestDiv = -1;
var inputId = document.getElementById("inputField").value;
for(var i=0; i<divs.length; i++)
{
if(Math.abs(inputId - closestDiv) > Math.abs(inputId - divs[i].id) || closestDiv == -1)
{
closestDiv = divs[i].id;
for (var x = 0; x < divs.length; x++) {
divs[x].style.display = 'none';
}
divs[i].style.display = "block";
}
}
});
See it Live: jsfiddle.net

Insert multiple rows and columns to a table in html dynamically using javascript code

I am trying to insert multiple rows and columns to create a table in html dynamically by selecting the number of rows and columns in dropdown list using javascript code like in MS Word.
For example if I select number of rows as 5 and number of columns as 5 from the dropdown list of numbers. 5 rows and 5 columns should get displayed.
My question is how can I add multiple rows and columns dynamically to create a table by selecting the number of rows and columns from the drop down list.
Since, <table> element is the one of the most complex structures in HTML, HTML DOM provide new interface HTMLTableElement with special properties and methods for manipulating the layout and presentation of tables in an HTML document.
So, if you want to accomplish expected result using DOM standards you can use something like this:
Demo old
Demo new
HTML:
<ul>
<li>
<label for="column">Add a Column</label>
<input type="number" id="column" />
</li>
<li>
<label for="row">Add a Row</label>
<input type="number" id="row" />
</li>
<li>
<input type="button" value="Generate" id="btnGen" />
<input type="button" value="Copy to Clipboard" id="copy" />
</li>
</ul>
<div id="wrap"></div>
JS new:
JavaScript was improved.
(function (window, document, undefined) {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
btnCopy = document.getElementById("btnCopy");
btnGen.addEventListener("click", generateTable);
btnCopy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
tBody = newTable.createTBody(),
nOfColumns = parseInt(setColumn.value, 10),
nOfRows = parseInt(setRow.value, 10),
row = generateRow(nOfColumns);
newTable.createCaption().appendChild(document.createTextNode("Generated Table"));
for (var i = 0; i < nOfRows; i++) {
tBody.appendChild(row.cloneNode(true));
}
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
}
function generateRow(n) {
var row = document.createElement("tr"),
text = document.createTextNode("cell");
for (var i = 0; i < n; i++) {
row.insertCell().appendChild(text.cloneNode(true));
}
return row.cloneNode(true);
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}(window, window.document));
JS old:
(function () {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
copy = document.getElementById("copy"),
nOfColumns = -1,
nOfRows = -1;
btnGen.addEventListener("click", generateTable);
copy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
caption = newTable.createCaption(),
//tHead = newTable.createTHead(),
//tFoot = newTable.createTFoot(),
tBody = newTable.createTBody();
nOfColumns = parseInt(setColumn.value, 10);
nOfRows = parseInt(setRow.value, 10);
caption.appendChild(document.createTextNode("Generated Table"));
// appendRows(tHead, 1);
// appendRows(tFoot, 1);
appendRows(tBody);
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.firstElementChild);
}
function appendColumns(tElement, count) {
var cell = null,
indexOfRow = [].indexOf.call(tElement.parentNode.rows, tElement) + 1,
indexOfColumn = -1;
count = count || nOfColumns;
for (var i = 0; i < count; i++) {
cell = tElement.insertCell(i);
indexOfColumn = [].indexOf.call(tElement.cells, cell) + 1;
cell.appendChild(document.createTextNode("Cell " + indexOfColumn + "," + indexOfRow));
}
}
function appendRows(tElement, count) {
var row = null;
count = count || nOfRows;
for (var i = 0; i < count; i++) {
row = tElement.insertRow(i);
appendColumns(row);
}
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}());
If you want to copy generated result to clipboard you can look at answer of Jarek Milewski - How to copy to the clipboard in JavaScript?
You can use this function to generate dynamic table with no of rows and cols you want:
function createTable() {
var a, b, tableEle, rowEle, colEle;
var myTableDiv = document.getElementById("DynamicTable");
a = document.getElementById('txtRows').value; //No of rows you want
b = document.getElementById('txtColumns').value; //No of column you want
if (a == "" || b == "") {
alert("Please enter some numeric value");
} else {
tableEle = document.createElement('table');
for (var i = 0; i < a; i++) {
rowEle = document.createElement('tr');
for (var j = 0; j < b; j++) {
colEle = document.createElement('td');
rowEle.appendChild(colEle);
}
tableEle.appendChild(rowEle);
}
$(myTableDiv).html(tableEle);
}
}
Try something like this:
var
tds = '<td>Data'.repeat(col_cnt),
trs = ('<tr>'+tds).repeat(row_cnt),
table = '<table>' + trs + '</table>;
Then place the table in your container:
document.getElementById('tablePreviewArea').innerHTML = table;
Or with JQuery:
$('#tablePreviewArea').html(table);
Here is the JSFiddle using native js.
Here is the JSFiddle using jQuery.
About the string repeat function
I got the repeat function from here:
String.prototype.repeat = function( num )
{
return new Array( num + 1 ).join( this );
}
I had one sample code...try this and modify it according to your requirement. May it helps you out.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<style type="text/css">
#mytab td{
width:100px;
height:20px;
background:#cccccc;
}
</style>
<script type="text/javascript">
function addRow(){
var root=document.getElementById('mytab').getElementsByTagName('tbody')[0];
var rows=root.getElementsByTagName('tr');
var clone=cloneEl(rows[rows.length-1]);
root.appendChild(clone);
}
function addColumn(){
var rows=document.getElementById('mytab').getElementsByTagName('tr'), i=0, r, c, clone;
while(r=rows[i++]){
c=r.getElementsByTagName('td');
clone=cloneEl(c[c.length-1]);
c[0].parentNode.appendChild(clone);
}
}
function cloneEl(el){
var clo=el.cloneNode(true);
return clo;
}
</script>
</head>
<body>
<form action="">
<input type="button" value="Add a Row" onclick="addRow()">
<input type="button" value="Add a Column" onclick="addColumn()">
</form>
<br>
<table id="mytab" border="1" cellspacing="0" cellpadding="0">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
Instead of button , you can use select menu and pass the value to variable. It will create row ,column as per the value.

Categories

Resources