can't use If - Else element exists in Javascript - javascript

I wrote a JS function to create a table in html and JS I want to click submit and after that the table to be created but I dont want the Submit button to create another table if clicked again
I tried to use IF - Else statements in the function but It's not working
code:
Button:
document.getElementById("btn_submit").addEventListener("click",sizeGrid)
function
function makeGrid(x,y) {
event.preventDefault();
if (document.getElementById('tbl') != null)
{
return;
}
else
{
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table');
for(var i = 0; i < x; i++){
var tr = tbl.insertRow();
for(var j = 0; j<y; j++){
var td= tr.insertCell()
}
}
body.append(tbl);
paint()
}
}
HTML
<h2>Design Canvas</h2>
<table id="pixelCanvas">
</table>
The table gets created two times after I click submit two times

You should set the tbl's id to 'tbl' by tbl.id = 'tbl'.

You are doing the check on the id of the table but never assign one.
function makeGrid(x,y) {
event.preventDefault();
if (document.getElementById('tbl') != null) {
return;
} else {
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table');
tbl.id = "tbl"; // Assign the id for the check
for(var i = 0; i < x; i++){
var tr = tbl.insertRow();
for(var j = 0; j<y; j++){
var td= tr.insertCell()
}
}
body.append(tbl);
paint();
}
};

Related

How to check a table is empty or not using javascript

So i have a script like this to make a 2x2 table by javascript
function createtable(){
var tbl = document.getElementById('x');
if (tbl.contains()==false){
tbl.setAttribute('border', '1');
var tbdy = document.createElement('tbody');
for (var i = 0; i < 2; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
var td = document.createElement('td');
tr.appendChild(td);
td.style.height='50px';
td.style.width='50px';
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
}
<form>
<input type="button" value="Create Table" onclick="createtable()"> <br>
</form>
<table id="x"> </table>
I want to check if table x contains anything or not to create itself. Im trying to use the contains() to check but it doesnt work.
You can check the number of rows in the table:
var x = document.getElementById("myTable").rows.length;
See reference here: https://www.w3schools.com/jsref/coll_table_rows.asp
Using this:
var tbl = document.getElementById('x');
if (tbl.rows.length == 0) {
// empty
}
If you want to check if there are any inside table do this
document.getElementById("myTable").rows.length
More info here
you can Check the Row Counts
var tbl = document.getElementById('x');
if(tbl.rows.length==0){
}
if the tbl.rows.length is 0 that means the table don't have any rows
There are multiple ways. One of way, you can use childElementCount property.
if (tbl.childElementCount==0)
{
}
For more details you can refere link
In this case, since there are no child elements or text nodes in your table, you can just check to see if the innerHTML property is falsy. This prevents your createtable function from appending additional children after the function has been run once. For example:
function createtable() {
var tbl = document.getElementById('x');
if (!tbl.innerHTML) {
var tbdy = document.createElement('tbody');
tbl.setAttribute('border', '1');
for (var i = 0; i < 2; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
var td = document.createElement('td');
tr.appendChild(td);
td.style.height = '50px';
td.style.width = '50px';
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
}
}
<form>
<input type="button" value="Create Table" onclick="createtable()">
<br>
</form>
<table id="x"></table>
Plain javascript:
!![].length
or use Lodash
_.head([]);
// => undefined

how to add checkboxes in cells of first column of HTML table?

I am working on an app development which will read through my mailbox and list all the unread e-mails in a HTML table on my web-app upon click of a button. Below is the code which I have made while researching through google which solves for the purpose.
<!DOCTYPE html>
<html>
<body>
<button onclick="groupFunction()">Click me</button>
<table id="tblContents">
<tr onclick="tableClickTest()">
<th>Sender</th>
<th>Sent_Date</th>
<th>Received_By</th>
<th>Received_Date</th>
<th>Subject</th>
</tr>
</table>
<script>
function RowSelection()
{
var table = document.getElementById("tblContents");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
}
function tableText(tableCell) {
alert(tableCell.innerHTML);
}
function PopulateTable()
{
var objOutlook = new ActiveXObject("Outlook.Application");
var session = objOutlook.Session;
//alert(session.Folders.Count)
for(var folderCount = 1;folderCount <= session.Folders.Count; folderCount++)
{
var folder = session.Folders.Item(folderCount);
//alert(folder.Name)
if(folder.Name.indexOf("Premanshu.Basak#genpact.com")>=0)
{
for(var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++)
{
var sampleFolder = folder.Folders.Item(subFolCount);
//alert(sampleFolder.Name)
if(sampleFolder.Name.indexOf("test1")>=0)
{
for(var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++)
{
var itm = sampleFolder.Items.Item(itmCount);
if(!itm.UnRead)
continue;
var sentBy = itm.SenderName;
var sentDate = itm.SentOn;
var receivedBy = itm.ReceivedByName;
var receivedDate = itm.ReceivedTime;
var subject = itm.ConversationTopic;
// var contents = itm.Body;
var tbl = document.getElementById("tblContents");
if(tbl)
{
var tr = tbl.insertRow(tbl.rows.length);
// tr.onclick(tableClickTest())
if(tbl.rows.length%2 != 0)
tr.className = "alt";
var tdsentBy = tr.insertCell(0);
var tdsentDate = tr.insertCell(1);
var tdreceivedBy = tr.insertCell(2);
var tdreceivedDate = tr.insertCell(3);
var tdsubject = tr.insertCell(4);
// var tdcontents = tr.insertCell(5);
tdsentBy.innerHTML = sentBy;
tdsentDate.innerHTML = sentDate;
tdreceivedBy.innerHTML = receivedBy;
tdreceivedDate.innerHTML = receivedDate;
tdsubject.innerHTML = subject;
// tdcontents.innerHTML = contents;
}
//itm.UnRead = false;
}
break;
}
}
break;
}
}
return;
}
function groupFunction()
{
PopulateTable()
RowSelection()
}
</script>
</body>
</html>
The thing that I am now looking for and is unable to do is how do I add a checkbox in the first column in each row. Also upon checking this checkbox the entire row should get highlighted so that I can perform specific task on all the selected items.
As far as I have understood your code, your first column's data is being set as:
tdsentBy.innerHTML = sentBy;
So in the same line, you can add textbox as a string as:
var cbox = "<div class='select-box'>
<input type='checkbox' name='selectBox' class='select-row'>
</div?>"
tdsentBy.innerHTML = cbox + sentBy;
In this way, a checkbox will always be available in first column of every row.
Now in RowSelection function, to bind event you can do something like:
var checkBox = table.rows[i].cells[j].querySelector(".select-row");
checkBox.addEventListener("click",function(evt){
});

javascript change table rows background color dynamically for setinterval

I change the background of rows to dynamically for setinterval but not working.
if clicked the button, change class name as the rows in the table.
My codes:
HTML Code:
<table id="table">
<tr>
<td>AAA11</td>
<td>BBB11</td>
</tr>
..
..
</table>
<button id="btn">click</button>
CSS Codes
.red { background-color: red; }
JS Codes
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
// My func
function func(){
for (var i = 0; i < rows.length; i++) {
var index=0;
var c = rows[i].className;
if(c!="red") {
index=i;
} else {
index = i+1;
}
sec(index);
}
setInterval(func(), 2000);
}
// Change class name the rows
function sec(index){
for (var i = 0; i < rows.length; i++) {
if(index==i) {
rows[index].className="red";
}
if(index!=i ){
rows[index].className="null";
}
}
}
$('#btn').click(function(){
setInterval(func(), 2000);
});
you reset all other lines, except the last row with in the "sec" function.
if(index!=i ){
rows[index].className="null";
}
delete that part and it should work like you wanted
...tough i don't get what you want to do, since all you're doing is setting all rows backgrounds...if you want to reset the red ones, don't use your sec() function...try this instead:
function func(){
for (var i = 0; i < rows.length; i++) {
var index=0;
var c = rows[i].className;
if(c=="red") {
rows[i].className="";
} else {
rows[i].className="red";
}
}
}
[edit]
...after it's cleared what OP wanted to do:
http://jsfiddle.net/bzWV2/1/
[edit2]
...easier approach:
http://jsfiddle.net/bzWV2/2/
You could do something like that:
var $table = $("#table");
var $rows = $table.find("tr");
var func = function(){
var curIndex = $rows.filter('.red').index(),
nextIndex = curIndex === $rows.length - 1?0:++curIndex;
$rows.eq(nextIndex).addClass('red').siblings().removeClass('red');
}
$('#btn').click(function(){
$rows.eq(0).addClass('red');
setInterval(func, 2000);
});
DEMO
function highlight(element)
{
$('tr').removeClass('red');
el = (!element)? $('tr:first') : element;
el.addClass('red');
next_el = el.next('tr');
var el = (next_el.length == 0)? $('tr:first'): next_el;
setTimeout(function(){ highlight(el) }, 1000);
}
setTimeout(function(){ highlight() }, 1000);
http://fiddle.jshell.net/TFcUS/2/

How to check value of table td?

I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name

Javascript table row <tr> onclick function not executing

I'm trying to have each table row clicked to be highlighted in a color and I'm handling this with a class name but the onclick function is not executing, I tried print statement inside the onclick function to check if it is entering but it's just not.
Here is the JS code related to that part:
var rows = document.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++)
{
rows[i].onclick = function() {
this.className = "highlighted";
}
}
Anyone know why this function isn't getting entered?
EDIT: I realized the mistake in the rows variable and I corrected it but the function is still not getting entered and I have no errors on my JS console
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
row.className = "highlighted";
};
};
currentRow.onclick = createClickHandler(currentRow);
}
Use this it will works....
Use this code. Your table rows must have an attribute name with the value "tr" to make this work :
var rows = document.getElementsByName("tr");
for (var i = 0; i < rows.length; i++)
{
rows[i].onclick = function() {
this.className = "highlighted";
}
}
use getElementsByTagName instead of getElementsById.
Try this
var rows = document.getElementsByTagName("tr");
Add semicolon
rows[i].onclick = function() {
this.className = "highlighted";
}; // here
It works for me .. Check here : JS Fiddle

Categories