table.insertRow from button in table doesn't work - javascript

Why the button "proba2" adds row in the table, but the button "Insert", who is in the table - adds row, which disappears at the function end?
My code is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Parameter AutoCgen</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
table,
th,
td {
padding: 10pt;
border-style: solid;
border-width: 1pt;
border-collapse: collapse;
text-align: center;
white-space: nowrap;
margin: auto;
}
table {
width: auto;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
input[type=text] {
background-color: transparent;
border-width: 0px;
}
</style>
<script>
'use strict';
var proba = function() {
for (var r of document.getElementsByTagName('table')[0].rows)
for (var d of r.cells) console.log(d.innerHTML);
}
var ins_after = function(obj) {
obj = obj || window.event;
var r = document.getElementsByTagName('table')[0].insertRow(obj.parentNode.parentNode.rowIndex);
var c1 = r.insertCell(0);
var c2 = r.insertCell(1);
var c3 = r.insertCell(2);
c1.innerHTML = 'drugo_ne6to';
alert(c1);
}
</script>
</head>
<body>
<form>
<table>
<caption style='font-size: 1.5em;'>Parameters list</caption>
<tr>
<th>Insert after</th>
<th>Delete</th>
<th>Parameter name</th>
</tr>
<tr>
<td>
<button onclick="ins_after(this);">Insert</button>
</td>
<td>ne6to</td>
<td>
<input type="text" name="property">
</td>
</tr>
</table>
</form>
<button onclick="proba();">proba1</button>
<button onclick="ins_after(this);">proba2</button>
</body>
</html>
The two buttons have the same one callback function on onclick event.
I try this in Chrome and Mozilla and the result is the same.
When I press "Insert" the new row appears in the table, I use alert to can see this, because after the function end, the row disappears again.
Also when I add several rows with button "proba2" and after that try the button "Insert" - it adds new row, then all new created rows disappears at the callback function end.
Apologize if this is trivial, but I'm new to JS.

It is disappearing because your button is in a form, so it is refreshing the page each time.
Try and add event.preventDefault(); at the end of your function to prevent the default functionality of the button in the form.
Here is a working example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Parameter AutoCgen</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
table, th, td {
padding: 10pt;
border-style: solid;
border-width: 1pt;
border-collapse: collapse;
text-align: center;
white-space: nowrap;
margin: auto;
}
table {
width: auto;
}
tr:nth-child(even) {background-color: #f2f2f2;}
input[type=text] {
background-color: transparent;
border-width: 0px;
}
</style>
<script>
'use strict';
var proba = function () {
for (var r of document.getElementsByTagName('table')[0].rows)
for (var d of r.cells) console.log(d.innerHTML);
}
var ins_after = function (obj) {
obj = obj || window.event;
var r = document.getElementsByTagName('table')[0].insertRow(obj.parentNode.parentNode.rowIndex);
var c1 = r.insertCell(0);
var c2 = r.insertCell(1);
var c3 = r.insertCell(2);
c1.innerHTML = 'drugo_ne6to';
event.preventDefault();
//alert(c1);
}
</script>
</head>
<body>
<form>
<table>
<caption style='font-size: 1.5em;'>Parameters list</caption>
<tr>
<th>Insert after</th>
<th>Delete</th>
<th>Parameter name</th>
</tr>
<tr>
<td>
<button onclick="ins_after(this);">Insert</button>
</td>
<td>ne6to</td>
<td>
<input type="text" name="property">
</td>
</tr>
</table>
</form>
<button onclick="proba();">proba1</button>
<button onclick="ins_after(this);">proba2</button>
</body>
</html>

A button inside a form has by default type="submit" and by clicking on it you will submit the form and reload the page, resetting your table rows (check the accepted answer here Disable form auto submit on button click)
To avoid this kind of behavior add type="button" to your "Insert" button inside the table like this:
<form>
<table>
<caption style='font-size: 1.5em;'>Parameters list</caption>
<tr>
<th>Insert after</th>
<th>Delete</th>
<th>Parameter name</th>
</tr>
<tr>
<td>
<button type="button" onclick="ins_after(this);">Insert</button>
</td>
<td>ne6to</td>
<td>
<input type="text" name="property">
</td>
</tr>
</table>
</form>

Related

JS in HTML gets stuck on if statements

My objective is to create a web game where a country name is given and the user must enter the correct capital of that country. A new row is then inserted with the country and answer and whether it's correct and a new country is shown. I have both the random country selector and insert new row working when I press the button with the id of "pr2__submit".
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>YourName 20200000</title>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="jquery/css/ui-lightness/jquery-ui-1.10.0.custom.css" rel="stylesheet" />
<link href="./capital_game.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Bakbak+One&family=Oswald:wght#700&display=swap" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" rel="stylesheet">
<style>
table {
margin-left: auto;
margin-right: auto;
table-layout: fixed;
width: 850px;
border-collapse: collapse;
}
th, td {
padding-bottom: 15px;
text-align: left;
border-bottom: 2px solid #D3D3D3;
}
</style>
</head>
<body>
<script src="jquery/js/jquery-1.9.0.min.js"></script>
<script src="jquery/js/jquery-ui-1.10.0.custom.min.js"></script>
<script src="./country_capital_pairs.js"></script>
<script src="./capital_game.js"></script>
<!--Your HTML here-->
<h1 style="font-size:70px; text-align: center; font-family: 'Bakbak One', cursive;" >Name the capital <i class="far fa-flag"></i></h1>
<script>
function randomCountry(){
let x = Math.floor(Math.random() * pairs.length);
document.getElementById("pr2__question").innerHTML = pairs[x].country;
let y = pairs[x].capital;
}
</script>
<script>
function focusInput() {
document.getElementById("pr2__answer").focus();
document.getElementById("pr2__answer").value = "";
}
</script>
<script>
function newRow() {
let guess = document.getElementById("pr2__answer").value;
var table = document.getElementById("myTable");
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
break;
}
</script>
<table id="myTable" style="font-size:200%;" class="center">
<tr style="border-bottom: 3px solid #330066; font-family: 'Oswald', sans-serif;">
<th>Country</th>
<th>Capital</th>
<th>Answer</th>
</tr>
<tr>
<td id="pr2__question"></td>
<td><input id="pr2__answer" type="text" placeholder="Your answer" autofocus><br></td>
<td> <button id="pr2__submit" onclick="newRow(); randomCountry(); focusInput();">See Answer</button> </td>
</tr>
<tr>
<td id="lastQuestion"></td>
<td id="lastAnswer">No entry to show</td>
<td id="correctAnswer"></td>
</tr>
</table>
<script>
randomCountry();
</script>
<script>
var inputText = document.getElementById("pr2__answer");
inputText.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("pr2__submit").click();
}
});
</script>
</body>
</html>
But when I try to add an if statement to determine whether the correct answer was input it does not work, and the random country selector and and insert new row stop working.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>YourName 20200000</title>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="jquery/css/ui-lightness/jquery-ui-1.10.0.custom.css" rel="stylesheet" />
<link href="./capital_game.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Bakbak+One&family=Oswald:wght#700&display=swap" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" rel="stylesheet">
<style>
table {
margin-left: auto;
margin-right: auto;
table-layout: fixed;
width: 850px;
border-collapse: collapse;
}
th, td {
padding-bottom: 15px;
text-align: left;
border-bottom: 2px solid #D3D3D3;
}
</style>
</head>
<body>
<script src="jquery/js/jquery-1.9.0.min.js"></script>
<script src="jquery/js/jquery-ui-1.10.0.custom.min.js"></script>
<script src="./country_capital_pairs.js"></script>
<script src="./capital_game.js"></script>
<!--Your HTML here-->
<h1 style="font-size:70px; text-align: center; font-family: 'Bakbak One', cursive;" >Name the capital <i class="far fa-flag"></i></h1>
<script>
function randomCountry(){
let x = Math.floor(Math.random() * pairs.length);
document.getElementById("pr2__question").innerHTML = pairs[x].country;
let y = pairs[x].capital;
}
</script>
<script>
function focusInput() {
document.getElementById("pr2__answer").focus();
document.getElementById("pr2__answer").value = "";
}
</script>
<script>
function newRow() {
let guess = document.getElementById("pr2__answer").value;
if (guess === y) {
var table = document.getElementById("myTable");
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
break;
}
}
</script>
<table id="myTable" style="font-size:200%;" class="center">
<tr style="border-bottom: 3px solid #330066; font-family: 'Oswald', sans-serif;">
<th>Country</th>
<th>Capital</th>
<th>Answer</th>
</tr>
<tr>
<td id="pr2__question"></td>
<td><input id="pr2__answer" type="text" placeholder="Your answer" autofocus><br></td>
<td> <button id="pr2__submit" onclick="newRow(); randomCountry(); focusInput();">See Answer</button> </td>
</tr>
<tr>
<td id="lastQuestion"></td>
<td id="lastAnswer">No entry to show</td>
<td id="correctAnswer"></td>
</tr>
</table>
<script>
randomCountry();
</script>
<script>
var inputText = document.getElementById("pr2__answer");
inputText.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("pr2__submit").click();
}
});
</script>
</body>
</html>

Set another button background color in one button onclick() function

I am trying to change button A background color to color 1 when clicked, and at the same time set button B color to color 2.
Same thing for when clicking button B.
The surprising thing is tow blocks code are totally symmetry, but one block work but another one block does not work.
How could it be?
In my main_js:
"function switchVisible_dgc() {
......
var color = '#3e8e41';
$("#dgc_click").css('background-color', color);
color='#325CA8';
$("#agc_click").css('background-color', color);
}
function switchVisible_agc() {
......
var color = '#3e8e41';
$("#agc_click").css('background-color', color);
color='#325CA8';
$("#dgc_click").css('background-color', color);
}
in my html:
<td width="0">
</td>
<td width="250">
<button class="button button5"
onclick="switchVisible_agc()"id="agc_click">Agc</button>
</td>
</td>
<td width="250">
<button class="button button5"
onclick="switchVisible_dgc()"id="dgc_click">Dgc</button>
</td>
</table>`
It might be something like this. You might include jQuery if you want.
It would be better to use CSS classes & dynamically assign them instead of modifying style attribute of elements directly.
Variables in this script are global because some outer closure assumed.
const buttons = document.querySelectorAll(`.button5`);
const switchColors = colors => {
buttons.forEach( (element, index) => {
element.style = `background-color: ${colors[index]}`
});
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
</table>
<td width="250">
<button id="agc_click" class="button button5" onclick="switchColors(['red', 'blue'])">Agc</button>
</td>
<td width="250">
<button id="dgc_click" class="button button5" onclick="switchColors(['green', 'yellow'])">Dgc</button>
</td>
</table>
</body>
</html>
UPD: In case if two pre-determined colors should be switched, the code could also be like:
const buttons = document.querySelectorAll(`.button5`);
const colors = [`#325CA8`, `#3E8E41`];
const switchColors = () => {
colors.reverse();
buttons.forEach( (element, index) => {
element.style = `background-color: ${colors[index]}`
});
};
You can do it simply by using addClass() and removeClass().
$('#agc_click').click(function(){
$('#agc_click, #dgc_click').removeClass('b2');
$('#agc_click, #dgc_click').addClass('b1');
});
$('#dgc_click').click(function(){
$('#dgc_click, #agc_click').removeClass('b2');
$('#dgc_click, #agc_click').addClass('b2');
});
html,
body {
height: 100%;
padding: 0;
margin: 0;
}
table {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
.b1 {
background-color: red !important;
}
.b2 {
background-color: blue !important;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<table>
<tr>
<td>
<button class="button button5" id="agc_click">Agc</button>
</td>
<td>
<button class="button button5" id="dgc_click">Dgc</button>
</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>

Writing in table <td> using Javascript with document.getElementById("Table").rows[i].cells[j].??? Or any other possible ways

How can I write in a table <td> using Javascript with document.getElementById("Table").rows[i].cells[j]? Or any other possible ways?
I want to write stuff into the <td></td> with javascript.
I used this code for the first part, but when I reused it, it didn't work. If it helps, the table was generated with javascript:
var cell = document.createElement("td");
var cellText = document.createTextNode(i+j);
cell.appendChild(cellText);
See create table using JavaScript:
var td = document.createElement('td');
td.appendChild(document.createTextNode('text'))
Here is a working example, with a basic table created in the markup.
// save the table to a var
var table = document.getElementById('my_table');
// save table body to a var. select the first occurrence of tbody element with [0]
var tableRef = table.getElementsByTagName('tbody')[0];
// save new row tr to a variable. this generates a tr
var newRow = tableRef.insertRow(tableRef.rows.length);
// insert a cell into newRow at index 0, 1, and 2, the td's for this row
var newTD1 = newRow.insertCell(0);
var newTD2 = newRow.insertCell(1);
var newTD3 = newRow.insertCell(2);
// create a text node for the TD
var tdText1 = document.createTextNode('cell text 1');
// add the text to the newly generated newTD1
newTD1.appendChild(tdText1);
// create a text node for the TD
var tdText2 = document.createTextNode('cell text 2');
// add the text to the newly generated newTD2
newTD2.appendChild(tdText2);
// create a text node for the TD
var tdText3 = document.createTextNode('cell text 3');
// add the text to the newly generated newTD3
newTD3.appendChild(tdText3);
/* table styles */
#my_table {
border-collapse: collapse;
border: 4px solid black;
margin: 0 auto;
text-align: center;
}
/* table tr, td styles */
#my_table th,
#my_table td {
border: 2px solid black;
}
/* table header styles */
#my_table th {
background-color: #33c6ff;
color: #000;
width: 33%;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<table id='my_table'>
<thead>
<tr>
<th id='table_header' colspan='3'>Table Title</th>
</tr>
<tr>
<th>Header Row 1</th>
<th>Header Row 2</th>
<th>Header Row 3</th>
</tr>
</thead>
<tbody id='table_body'>
</tbody>
</table> <!-- ends table -->
</body>
</html>

Toggle class which be clicked in multiple class - DOM

I try to toggle class when td clicked in multiple class but it does not work. I prefer working on DOM.
window.onload = function() {
var seats = document.getElementsByClassName('seat');
for(var i = 0; i < seats.length; i++) {
seats[i].onclick = function() {
seats[i].classList.toggle = 'selected';
}
}
}
td {
width: 30px;
height: 30px;
background-color: red;
color: white;}
td.selected {
background-color: black;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td class="seat">1</td>
<td class="seat">2</td>
<td class="seat">3</td>
<td class="seat">4</td>
<td class="seat">5</td>
</tr>
</table>
</body>
</html>
http://jsbin.com/kufemuhagi/edit?html,css,js,output
Problem :
You've a scope problem in the posted code where your variable i counldn't found inside the event handler, this variable is accessible just outside of it, to fix this you need to wrap the assignment of the event listener in a closure, like :
for (var i = 0; i < seats.length; i++) {
(function(i) {
seats[i].onclick = function() {
seats[i].classList.toggle('selected');
}
})(i);
}
window.onload = function() {
var seats = document.getElementsByClassName('seat');
for (var i = 0; i < seats.length; i++) {
(function(i) {
seats[i].onclick = function() {
console.log(i);
seats[i].classList.toggle('selected');
}
})(i);
}
}
td {
width: 30px;
height: 30px;
background-color: red;
color: white;
}
td.selected {
background-color: black;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td class="seat">1</td>
<td class="seat">2</td>
<td class="seat">3</td>
<td class="seat">4</td>
<td class="seat">5</td>
</tr>
</table>
</body>
</html>
My suggestion :
Separate you logic and use addEventListener() to attach the events, then use this to toggle your class, like the sample below shows.
window.onload = function() {
var seats = document.getElementsByClassName('seat');
var clickHandler = function() {
this.classList.toggle('selected');
};
for (var i = 0; i < seats.length; i++) {
seats[i].addEventListener('click', clickHandler, false);
}
}
div.selected {
background-color: green;
}
<div class="seat">Div 1</div>
<div class="seat">Div 2</div>
<div class="seat">Div 3</div>
<div class="seat">Div 4</div>
The Problem with your code is that the variable i isn't defined per iteration it is defined in the function scope. That means that the for loop you have goes trough every element and assigns the onclick handler to each "seat" but after the last iteration the i variable will be set to an out-of-bounds index since the for loop does the i++ expression after each iteration. The problem is your onclick handler refers to the i variable, which is set to an out-of-bounds index, so that the seats[i] expression returns an undefined value. You can fix this by using the this statement inside the onclick handler or by using the first argument which is the click event. The click event contains a target which refers to the clicked EventTarget (this should be your "seat" element).
function handleSeatClick(ev) {
var seat = ev.target;
if(seat.classList.contains('selected')){
seat.classList.remove('selected');
} else {
seat.classList.add('selected');
}
}
window.onload = function() {
var seats = document.getElementsByClassName('seat');
for(var i = 0; i < seats.length; i++) {
seats[i].addEventListener('click', handleSeatClick);
}
}
td {
width: 30px;
height: 30px;
background-color: red;
color: white;}
td.selected {
background-color: black;}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td class="seat">1</td>
<td class="seat">2</td>
<td class="seat">3</td>
<td class="seat">4</td>
<td class="seat">5</td>
</tr>
</table>
</body>
</html>
Hope this will help.
window.onload = function() {
var seats = document.getElementsByClassName('seat');
for(var i = 0; i < seats.length; i++) {
seats[i].onclick = function() {
this.classList.toggle('selected'); //this will refer current object here and toggle is function
}
}
}
td {
width: 30px;
height: 30px;
background-color: red;
color: white;}
td.selected {
background-color: black;}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td class="seat">1</td>
<td class="seat">2</td>
<td class="seat">3</td>
<td class="seat">4</td>
<td class="seat">5</td>
</tr>
</table>
</body>
</html>

Search and display the table values while typing

I refer the following code from stack-overflow itself.but it will not working, anyone can tell what should I update this code.
var $rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
body {padding: 20px;}
input {margin-bottom: 5px; padding: 2px 3px; width: 209px;}
td {padding: 4px; border: 1px #CCC solid; width: 100px;}
<html>
<head>
<title>Search Event</title>
<script type="text/javascript" src="search.js"></script>
<link href="search.css" rel="stylesheet" type="text/css">
</head>
<body>
<center><input type="text" id="search" placeholder="Type to search"></center>
<center><table id="table">
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
</table></center>
</body>
</html>
with these simple concept am struggling so far.so please help me.
If i type ap or apple means the correspondent values only should
display other than should hide
Note , not certain if expected result is to toggle td elements ? As js at Question appear to toggle tr elements ? To toggle td elements where text input matches td text, try adding .find("td") before call to .show() to substitute filtering td elements for parent tr elements
If input "app" only td containing text "Apple" should be displayed
var $rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.find("td").show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
body {padding: 20px;}
input {margin-bottom: 5px; padding: 2px 3px; width: 209px;}
td {padding: 4px; border: 1px #CCC solid; width: 100px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<html>
<head>
<title>Search Event</title>
<script type="text/javascript" src="search.js"></script>
<link href="search.css" rel="stylesheet" type="text/css">
</head>
<body>
<center><input type="text" id="search" placeholder="Type to search"></center>
<center><table id="table">
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
</table></center>
</body>
</html>
code is not working because your "search.js" file need jquery
in you code Jquery file missing with jquery it's working fine
it must be
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="search.js"></script>
<link href="search.css" rel="stylesheet" type="text/css">
check this fiddle
Added jquery-1.9.1.js in html..
<head>
<title>Search Event</title>
<script type="text/javascript" src="search.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<link href="search.css" rel="stylesheet" type="text/css">
</head>
Fiddle

Categories