Javascript Sort not working after CRUD operation - javascript

I have this HTML table that works well when I sorted the hard-coded data, especially the first column, but after the sort, when CRUD operation happens (Add/Edit), it will call right away the arrTable.reverse() method. It will sort again right if we click the second column but not again after adding or editing the data.
**Update
**I just want that after I add or insert new row, I can only call the sort function, not the reverse.
cPrev = -1; // global var saves the previous c, used to
// determine if the same column is clicked again
function sortBy(c) {
rows = document.getElementById("data_table").rows.length - 1; // num of rows
columns = document.getElementById("data_table").rows[0].cells.length; // num of columns
arrTable = [...Array(rows)].map(e => Array(columns)); // create an empty 2d array
for (ro = 0; ro < rows; ro++) { // cycle through rows
for (co = 0; co < columns; co++) { // cycle through columns
// assign the value in each row-column to a 2d array by row-column
arrTable[ro][co] = document.getElementById("data_table").rows[ro].cells[co].innerHTML;
}
}
th = arrTable.shift(); // remove the header row from the array, and save it //c !== cPrev
// if (c === cPrev ){ // different column is clicked, so sort by the new column
if (c !== cPrev) { // different column is clicked, so sort by the new column
arrTable.sort(
function(a, b) {
if (a[c] === b[c]) {
return 0;
} else {
return (a[c] < b[c]) ? -1 : 1;
}
}
);
} else { // if the same column is clicked then reverse the array
arrTable.reverse();
}
cPrev = c; // save in previous c
arrTable.unshift(th); // put the header back in to the array
// cycle through rows-columns placing values from the array back into the html table
for (ro = 0; ro < rows; ro++) {
for (co = 0; co < columns; co++) {
document.getElementById("data_table").rows[ro].cells[co].innerHTML = arrTable[ro][co];
}
}
}
const removeSaveBtns = () => {
const saveBtns = document.querySelectorAll('.save');
saveBtns.forEach((btn, i) => {
btn.style.display = "none";
})
}
removeSaveBtns();
function edit_row(no) {
document.getElementById("edit_button" + no).style.display = "none";
document.getElementById("save_button" + no).style.display = "";
var name = document.getElementById("name_row" + no);
var name_data = name.innerHTML;
name.innerHTML = "<input type='text' id='name_text" + no + "' value='" + name_data + "'>";
}
function save_row(no) {
var name_val = document.getElementById("name_text" + no).value;
document.getElementById("name_row" + no).innerHTML = name_val;
document.getElementById("save_button" + no).style.display = "none";
document.getElementById("edit_button" + no).style.display = "";
}
function delete_row(no) {
document.getElementById("row" + no + "").outerHTML = "";
}
function addOne(button) {
console.log(button.nextElementSibling.innerHTML)
var spanEle = button.nextElementSibling;
var old = parseInt(spanEle.innerHTML)
spanEle.innerHTML = old + 1;
}
function add_row(no) {
var new_name = document.getElementById("new_name").value;
var new_city = document.getElementById("new_city").value;
if (new_name == "" || new_name == null) {
window.alert("Please Input Team");
return false;
}
var table = document.getElementById("data_table");
var table_len = (table.rows.length) - 1;
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'><td id='name_row" + table_len + "'>" + new_name + "</td><td id='name_city" + table_len + "'>" + new_city + "</td><td><input type='button' id='edit_button" + table_len + "' value='Edit' class='edit' onclick='edit_row(" + table_len + ")'> <input type='button' id='save_button" + table_len + "' value='Save' class='save' onclick='save_row(" + table_len + ")'> <input type='button' id='delete_button" + table_len + "' value='Delete' class='delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("new_name").value = "";
document.getElementById("new_city").value = "";
removeSaveBtns();
}
h1 {
font-size: 30px;
color: #fff;
text-transform: uppercase;
font-weight: 300;
text-align: center;
margin-bottom: 15px;
}
table {
width: 100%;
table-layout: fixed;
}
.tbl-header {
background-color: rgba(255, 255, 255, 0.3);
}
.tbl-content {
height: 300px;
overflow-x: auto;
margin-top: 0px;
border: 1px solid rgba(255, 255, 255, 0.3);
}
th {
padding: 10px 15px;
text-align: left;
font-weight: 500;
font-size: 12px;
color: #fff;
text-transform: uppercase;
}
td {
padding: 15px;
text-align: center;
vertical-align: middle;
font-weight: 300;
font-size: 12px;
color: #fff;
border-bottom: solid 1px rgba(255, 255, 255, 0.1);
}
#import url(https://fonts.googleapis.com/css?family=Roboto:400,500,300,700);
body {
background: -webkit-linear-gradient(left, #25c481, #25b7c4);
background: linear-gradient(to right, #25c481, #25b7c4);
font-family: 'Roboto', sans-serif;
}
section {
margin: 50px;
}
button {
background: linear-gradient(to bottom right, #EF4765, #FF9A5A);
border: 0;
border-radius: 12px;
color: #FFFFFF;
cursor: pointer;
display: inline-block;
font-family: -apple-system, system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-size: 16px;
font-weight: 500;
line-height: 2.5;
outline: transparent;
padding: 0 1rem;
text-align: center;
text-decoration: none;
transition: box-shadow .2s ease-in-out;
user-select: none;
-webkit-user-select: none;
touch-action: manipulation;
white-space: nowrap;
}
button:not([disabled]):focus {
box-shadow: 0 0 .25rem rgba(0, 0, 0, 0.5), -.125rem -.125rem 1rem rgba(239, 71, 101, 0.5), .125rem .125rem 1rem rgba(255, 154, 90, 0.5);
}
button:not([disabled]):hover {
box-shadow: 0 0 .25rem rgba(0, 0, 0, 0.5), -.125rem -.125rem 1rem rgba(239, 71, 101, 0.5), .125rem .125rem 1rem rgba(255, 154, 90, 0.5);
}
<h1>City</h1>
<div id="wrapper">
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<tbody>
<tr>
<th onclick="sortBy(0)">Countries</th>
<th onclick="sortBy(1)">City</th>
<th>Action</th>
</tr>
<tr id="row1">
<td id="name_row1">Germany</td>
<td id="name_city1">Berlin</td>
<td>
<input type="button" id="edit_button1" value="Edit" class="edit" onclick="edit_row('1')">
<input type="button" id="save_button1" value="Save" class="save" onclick="save_row('1')">
<input type="button" id="delete_button1" value="Delete" class="delete" onclick="delete_row('1')">
</td>
</tr>
<tr id="row2">
<td id="name_row2">Norway</td>
<td id="name_city2">Oslo</td>
<td>
<input type="button" id="edit_button2" value="Edit" class="edit" onclick="edit_row('2')">
<input type="button" id="save_button2" value="Save" class="save" onclick="save_row('2')">
<input type="button" id="delete_button2" value="Delete" class="delete" onclick="delete_row('2')">
</td>
</tr>
<tr id="row3">
<td id="name_row3">Brazil</td>
<td id="name_city3">Rio</td>
<td>
<input type="button" id="edit_button3" value="Edit" class="edit" onclick="edit_row('3')">
<input type="button" id="save_button3" value="Save" class="save" onclick="save_row('3')">
<input type="button" id="delete_button3" value="Delete" class="delete" onclick="delete_row('3')">
</td>
</tr>
<tr id="row4">
<td id="name_row4">Mexico</td>
<td id="name_city4">MX</td>
<td>
<input type="button" id="edit_button4" value="Edit" class="edit" onclick="edit_row('4')">
<input type="button" id="save_button4" value="Save" class="save" onclick="save_row('4')">
<input type="button" id="delete_button4" value="Delete" class="delete" onclick="delete_row('4')">
</td>
</tr>
<tr id="row4">
<td id="name_row5">Bahamas</td>
<td id="name_city5">Nassau</td>
<td>
<input type="button" id="edit_button5" value="Edit" class="edit" onclick="edit_row('5')">
<input type="button" id="save_button5" value="Save" class="save" onclick="save_row('5')">
<input type="button" id="delete_button5" value="Delete" class="delete" onclick="delete_row('5')">
</td>
</tr>
<tr>
<td><input type="text" id="new_name"></td>
<td><input type="text" id="new_city"></td>
<td><input type="button" class="add" onclick="add_row();" value="Add Row"></td>
</tr>
</tbody>
</table>
</div>
Thanks a lot.

Related

How to fix two decimal place problem with point .01 returning to 0

The problem is that when I type in a number such as 18.0 my code gets to 18, where I want my user to freely type in 18.06. But my code doesnt let the user go above 18.0.
My Fiddle https://jsfiddle.net/dev2804/cf8vwrbj/1/
function Process() {
var AUS = 1; //CURENY RATE CAN BE CHAGNED BUT THE COUNTRIES IT SELF WON'T, ITS NOT A PART OF THE ASSIGNMENT.
var YEN = 82;
var YAUN = 5;
var RUPIAH = 10000;
var val = event.target.value;
var country = {
"Australia": AUS,
"JapaneseYen": YEN,
"ChineseYuan": YAUN,
"IndonesianRupiah": RUPIAH
};
var countRate;
if (event.target.id == 'countryAustralia') {
countRate = AUS;
} else if (event.target.id == 'countryJapaneseYen') {
countRate = YEN;
} else if (event.target.id == 'countryChineseYuan') {
countRate = YAUN;
} else if (event.target.id == 'countryIndonesianRupiah') {
countRate = RUPIAH;
}
var text = "";
var i;
var rateMp = (val / countRate);
if (val > 0.01 || val < 0) {
for (var i in country) {
var currency = (rateMp * country[i]);
var input = document.querySelector('#country' + i); // select the input by it's ID, I used the country object to build the selector
input.value = currency; // assign the calculated value to the input
}
} else if (val == "") {
for (var i in country) {
var currency = "";
var input = document.querySelector('#country' + i);
input.value = currency;
}
} else if (val.toString() == "0") {
for (var i in country) {
var currency = 0.00;
var input = document.querySelector('#country' + i);
input.value = currency;
}
}
}
<Section class="container">
<Table>
<tr class="RowDesign">
<td class="CountryName">
<div class="CountryText">Australia</div>
</td><br>
<td>
<INPUT placeholder="AUD" type="number" Class="Country" ID="countryAustralia" list="CommonVal" oninput="Process();" onClick="Remove();" />
</td>
</tr>
<tr class="RowDesign">
<td class="CountryName">
<div class="CountryText">Japan</div>
</td><br>
<td>
<INPUT type="number" placeholder="JPY" Class="Country" ID="countryJapaneseYen" list="CommonVal" oninput="Process();" onClick="Remove();" />
</td>
</tr>
<tr class="RowDesign">
<td class="CountryName">
<div class="CountryText">China</div>
</td><br>
<td>
<INPUT type="number" placeholder="CNY" Class="Country" ID="countryChineseYuan" list="CommonVal" onInput="Process();" onClick="Remove();" />
</td>
</tr>
<tr class="RowDesign">
<td class="CountryName">
<div class="CountryText">Indonesia</div>
</td><br>
<td>
<INPUT type="number" placeholder="IDR" Class="Country" ID="countryIndonesianRupiah" list="CommonVal" oninput="Process();" onClick="Remove();" />
</td>
</tr>
<Datalist ID="CommonVal">
<option value=1>1</option>
<option value=10>10</option>
<option value=100>100</option>
<option value=500>500</option>
</Datalist>
</Table>
</Section>
I tried couple of if statements but didn't work. So now I have no idea on how to fix this bug.
You can try this, i updated you code:
<HTML>
<HEAD>
<TITLE>Currency Converter Protype4</TITLE>
</HEAD>
<BODY>
<Style>
body {
background-image: url(https://lh4.googleusercontent.com/-XplyTa1Za-I/VMSgIyAYkHI/AAAAAAAADxM/oL-rD6VP4ts/w1184-h666/Android-Lollipop-wallpapers-Google-Now-Wallpaper-2.png);
background-position: center;
background-size: cover;
background-repeat: no-repeat;
min-height: 100vh;
font-family: 'Roboto', sans-serif;
}
table{
border-collapse: collapse;
width: 360px;
height: 370px;
border-radius: 5px;
position: absolute;
top: 50%; /*Remember this */
left: 50%;
margin-top: -185px;
margin-left: -180px;
}
.RowDesign{
height: 80px;
background-color: #ccffff;
border: 10px solid #b3b3ff;
border-radius: 5px;
}
.container{
position: absolute;
top: 50%; /*Remember this */
left: 50%;
margin-top: -200px;
margin-left: -190px;
width: 380px;
height:400px;
background-color: #b3b3ff;
border: 3px solid #b3b3ff;
border-radius: 5px;
}
.CountryName{
padding-left: 8px;
padding-right: 18px;
padding-top: 5px;
text-align: center;
}
.ImgText{
width: 70px;
height: 45px;
border: 1px solid #fff;
}
.Country{
height: 30px;
width: 175px;
padding-left: 20px;
border: 2px solid #0066ff;
border-radius: 15px;
}
.Country:hover{
background-color: #e6e6ff;
}
.CountryText{
vertical-align: center;
visibility: hidden;
font-weight: Bold;
color: #3d2263;
}
.ImgText:hover ~ .CountryText{
visibility: visible;
}
input:focus {
background-color: #e6e6ff;
}
</Style>
<Section class="container">
<Table>
<tr class="RowDesign">
<td class="CountryName"><img class="ImgText" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/88/Flag_of_Australia_%28converted%29.svg/1600px-Flag_of_Australia_%28converted%29.svg.png" alt="Australia"><div class="CountryText">Australia</div></td><br>
<td><INPUT placeholder="AUD" type="number" Class="Country" ID="countryAustralia" list="CommonVal" oninput="validate(this);Process(event);" onClick="Remove();" ></td>
</tr>
<tr class="RowDesign">
<td class="CountryName"><img class="ImgText" src="https://upload.wikimedia.org/wikipedia/en/thumb/9/9e/Flag_of_Japan.svg/1280px-Flag_of_Japan.svg.png" alt="Japan"><div class="CountryText">Japan</div></td><br>
<td><INPUT type="number" placeholder="JPY" Class="Country" ID="countryJapaneseYen" list="CommonVal" oninput="validate(this);Process(event);" onClick="Remove();"></td>
</tr>
<tr class="RowDesign">
<td class="CountryName"><img class="ImgText" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Flag_of_the_People%27s_Republic_of_China.svg/510px-Flag_of_the_People%27s_Republic_of_China.svg.png" alt="ChineseYuan" height="60px" width="90px"><div class="CountryText">China</div></td><br>
<td><INPUT type="number" placeholder="CNY" Class="Country" ID="countryChineseYuan" list="CommonVal" onInput="validate(this);Process(event);" onClick="Remove();"></td>
</tr>
<tr class="RowDesign">
<td class="CountryName"><img class="ImgText" src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/Flag_of_Indonesia.svg/510px-Flag_of_Indonesia.svg.png" alt="IndonesianRupiah" ><div class="CountryText">Indonesia</div></td><br>
<td><INPUT type="number" placeholder="IDR" Class="Country" ID="countryIndonesianRupiah" list="CommonVal" step="any" oninput="validate(this);Process(event);" onClick="Remove();" ></td>
</tr>
<Datalist ID="CommonVal">
<option value=1>1</option>
<option value=10>10</option>
<option value=100>100</option>
<option value=500>500</option>
</Datalist>
</table>
</Section>
<SCRIPT LANGUAGE="javascript" TYPE="text/javascript">
var validate = function(e) {
var t = e.value;
//console.log(t)
/* e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t; */
// console.log(e.value )
}
function Process(event) {
var AUS = 1; //CURENY RATE CAN BE CHAGNED BUT THE COUNTRIES IT SELF WON'T, ITS NOT A PART OF THE ASSIGNMENT.
var YEN = 82;
var YAUN = 5;
var RUPIAH = 10000;
var val = event.target.value;
var country = {
"Australia": AUS,
"JapaneseYen": YEN,
"ChineseYuan": YAUN,
"IndonesianRupiah": RUPIAH
};
var countRate;
if (event.target.id=='countryAustralia'){
countRate = AUS;
}
else if (event.target.id=='countryJapaneseYen'){
countRate = YEN;
}
else if (event.target.id=='countryChineseYuan'){
countRate = YAUN;
}
else if (event.target.id=='countryIndonesianRupiah'){
countRate = RUPIAH;
}
var text = "";
var i;
var rateMp = (val/countRate);
if (val>0){
for (var i in country) {
var currency = (rateMp* country[i]);
var input = document.querySelector('#country' + i); // select the input by it's ID, I used the country object to build the selector
if (event.target.id!='country' + i){
input.value = currency; // assign the calculated value to the input
}
}
}
else if (val==""){
for (var i in country) {
var currency = "";
var input = document.querySelector('#country' + i);
input.value = currency;
}
}
else if (val.toString()=="0"){
for (var i in country) {
var currency = 0.00;
var input = document.querySelector('#country' + i);
input.value = currency;
}
}
}
function Remove(){}
</SCRIPT>
</BODY>
</HTML>
This is working same as you want.Thanks!!

Compare items in an array against table items in JavaScript, Beginner

I created a really basic table with 20 numbers inside. I have then bodged together a system which creates an array of 20 numbers and shuffles it, there is then a button which displays one position of the array at a time.
What I want to do, which I haven't been able to figure out yet, is to use the number that has been generated to change to background color of that same number in the table. So if I drew the number 20 it would be marked on the table.
Please could you respond with JavaScript only as jQuery is still a little unknown at the moment.
// This bit shuffles an array
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
// swap randomly chosen element with current element
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
// Array input
var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]);
//This bit calls the position of the array
var f = 0; // the index of the current item to show
function nextNumber() {
document
.getElementById('test')
.innerHTML = ranNums[f++]; // get the item and increment
if (f == ranNums.length) f = 0; // reset to first element if you've reached the end
}
body {
background-color: white;
color: black;
font-size: 20px;
font-family: "Lucida Grande", Verdana,Arial, Helvetica, sans-serif;
}
h1, th {
font-family: Georgia, "Times New Roman",Times, serif;
}
h1 {
font-size: 28px;
}
table {
border-collapse: separate;
border-spacing: 30px;
float: left;
}
th, td {
padding: 30px;
border: 2px black solid;
text-align: center;
width: 20%;
}
h2 {
}
button {
}
#item20 {
background-color: red;
}
<h1>Bingo!</h1>
<h2 id="test"></h2>
<table>
<tr>
<td id="item1"<h1>1</h1></td>
<td id="item2"<h1>2</h1></td>
<td id="item3"<h1>3</h1></td>
<td id="item4"<h1>4</h1></td>
<td id="item5"<h1>5</h1></td>
</tr>
<tr>
<td id="item6"<h1>6</h1></td>
<td id="item7"<h1>7</h1></td>
<td id="item8"<h1>8</h1></td>
<td id="item9"<h1>9</h1></td>
<td id="item10"<h1>10</h1></td>
</tr>
<tr>
<td id="item11"<h1>11</h1></td>
<td id="item12"<h1>12</h1></td>
<td id="item13"<h1>13</h1></td>
<td id="item14"<h1>14</h1></td>
<td id="item15"<h1>15</h1></td>
</tr>
<tr>
<td id="item16"<h1>16</h1></td>
<td id="item17"<h1>17</h1></td>
<td id="item18"<h1>18</h1></td>
<td id="item19"<h1>19</h1></td>
<td id="item20"<h1>20</h1></td>
</tr>
</table>
<button onclick="nextNumber()">Next Number</button>
Change your nextNumber method to also highlight the new random number selected
function nextNumber() {
var number = ranNums[f];
f++;
document.getElementById('test').innerHTML = number;
document.getElementById("item" + number).style.backgroundColor = "red";
if (f == ranNums.length) f = 0; // reset to first element if you've reached the end
}
Demo
// This bit shuffles an array
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i + 1));
// swap randomly chosen element with current element
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
// Array input
var ranNums = shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
//This bit calls the position of the array
var f = 0; // the index of the current item to show
function nextNumber() {
var number = ranNums[f];
f++;
document.getElementById('test').innerHTML = number;
document.getElementById("item" + number).style.backgroundColor = "red";
if (f == ranNums.length) f = 0; // reset to first element if you've reached the end
}
body {
background-color: white;
color: black;
font-size: 20px;
font-family: "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
}
h1,
th {
font-family: Georgia, "Times New Roman", Times, serif;
}
h1 {
font-size: 28px;
}
table {
border-collapse: separate;
border-spacing: 30px;
float: left;
}
th,
td {
padding: 30px;
border: 2px black solid;
text-align: center;
width: 20%;
}
h2 {}
button {}
#item20 {
background-color: red;
}
<h1>Bingo!</h1>
<h2 id="test"></h2>
<table>
<tr>
<td id="item1" <h1>1</h1>
</td>
<td id="item2" <h1>2</h1>
</td>
<td id="item3" <h1>3</h1>
</td>
<td id="item4" <h1>4</h1>
</td>
<td id="item5" <h1>5</h1>
</td>
</tr>
<tr>
<td id="item6" <h1>6</h1>
</td>
<td id="item7" <h1>7</h1>
</td>
<td id="item8" <h1>8</h1>
</td>
<td id="item9" <h1>9</h1>
</td>
<td id="item10" <h1>10</h1>
</td>
</tr>
<tr>
<td id="item11" <h1>11</h1>
</td>
<td id="item12" <h1>12</h1>
</td>
<td id="item13" <h1>13</h1>
</td>
<td id="item14" <h1>14</h1>
</td>
<td id="item15" <h1>15</h1>
</td>
</tr>
<tr>
<td id="item16" <h1>16</h1>
</td>
<td id="item17" <h1>17</h1>
</td>
<td id="item18" <h1>18</h1>
</td>
<td id="item19" <h1>19</h1>
</td>
<td id="item20" <h1>20</h1>
</td>
</tr>
</table>
<button onclick="nextNumber()">Next Number</button>
You could clean this up a bit, but this one uses a red class. The key is to target the box using document.getElementById("item" + randNum).className = "red";
I have added a resetNumbers() function and button to reset your classes. This is to display the reason why I chose to use a class. Originally I had it resetting after every button click, but if this is BINGO, that probably is not desired. I commented out where I was doing this, but you can still reset.
I prefer this to setting the background colour, as this is controlled through a css class instead, which is easier to manage.
// This bit shuffles an array
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
// swap randomly chosen element with current element
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
// Array input
var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]);
//This bit calls the position of the array
var f = 0; // the index of the current item to show
function nextNumber() {
var randNum = ranNums[f++];
document.getElementById('test').innerHTML = randNum; // get the item and increment
if (f == ranNums.length) f = 0; // reset to first element if you've reached the end
//resetNumbers();//uncomment if you do not want to reset - or remove if you never want this here
document.getElementById("item" + randNum).className = "red";
}
function resetNumbers() {
for (var i = 0; i < ranNums.length; i++) {
document.getElementById("item" + ranNums[i]).className = "";
}
}
body {
background-color: white;
color: black;
font-size: 20px;
font-family: "Lucida Grande", Verdana,Arial, Helvetica, sans-serif;
}
h1, th {
font-family: Georgia, "Times New Roman",Times, serif;
}
h1 {
font-size: 28px;
}
table {
border-collapse: separate;
border-spacing: 30px;
float: left;
}
th, td {
padding: 30px;
border: 2px black solid;
text-align: center;
width: 20%;
}
.red {
background-color: red;
}
<h1>Bingo!</h1>
<h2 id="test"></h2>
<table>
<tr>
<td id="item1"<h1>1</h1></td>
<td id="item2"<h1>2</h1></td>
<td id="item3"<h1>3</h1></td>
<td id="item4"<h1>4</h1></td>
<td id="item5"<h1>5</h1></td>
</tr>
<tr>
<td id="item6"<h1>6</h1></td>
<td id="item7"<h1>7</h1></td>
<td id="item8"<h1>8</h1></td>
<td id="item9"<h1>9</h1></td>
<td id="item10"<h1>10</h1></td>
</tr>
<tr>
<td id="item11"<h1>11</h1></td>
<td id="item12"<h1>12</h1></td>
<td id="item13"<h1>13</h1></td>
<td id="item14"<h1>14</h1></td>
<td id="item15"<h1>15</h1></td>
</tr>
<tr>
<td id="item16"<h1>16</h1></td>
<td id="item17"<h1>17</h1></td>
<td id="item18"<h1>18</h1></td>
<td id="item19"<h1>19</h1></td>
<td id="item20"<h1>20</h1></td>
</tr>
</table>
<button onclick="nextNumber()">Next Number</button>
<button onclick="resetNumbers()">Reset Numbers</button>

Textarea won't display values after hitting Reset

The reset button only appears once a conversion from Fahrenheit to Celsius is successfully done. It works fine. However, after hitting Reset, I cannot see values in the textarea when perform more conversions. I think the problem is most likely caused the two arrays in my codes. What do you think?
I have recreated the problem here: http://jsfiddle.net/wnna3646/
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Temperature Conversion</title>
<style type="text/css">
body { font: 1em calibri, arial; }
button {
background-color: transparent;
margin: 5px;
width: 300px;
}
h1, h2, h3, h4 { text-align: center; }
table {
border: 8px double;
margin-left: auto;
margin-right: auto;
padding: 2px;
height: 500px;
width: 30%;
}
td { border: 1px solid; }
td#topcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#midcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#bottomcell { text-align: center; }
textarea {
width: 250px;
height: 250px;
}
p {
word-spacing: 25px;
}
#Fahr {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#Cels {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#ftemp, #ctemp {
display: inline;
float: middle;
}
</style>
</head>
<body>
<main role="main">
<form id="myForm" onsubmit="return this.ftemp.value!=''">
<table>
<tr>
<td id="topcell">
<label for="Fahrenheit" id="Fahr">Fahrenheit:</label><input id="ftemp" onkeypress="return fNumericCharactersOnly(event)" onkeyup="this.form.Convertbtn.disabled = this.value==''; this.form.Avgbtn.disabled = this.value==''; if(!validnum(this.value)) this.value=''">
<br /><br />
<label for="Celsius" id="Cels" >Celsius:</label><input id="ctemp" readonly>
<br /><br /><br /><br /><br /><br />
<p>Fahrenheit Celsius</p>
</td>
</tr>
<tr>
<td id="midcell">
<br />
<textarea rows="5" id="txtArea" readonly></textarea>
</td>
</tr>
<tr>
<td id="bottomcell">
<input type="button" id="Convertbtn" value="Convert" accesskey="c" onclick="convertTemp(); counter++" disabled="disabled"/>
<input type="button" id="Avgbtn" value="Average" accesskey="a" onclick="averageTemp(); AddResetbutton()" disabled="disabled"/>
<div id="ButtonSpot"></div>
</td>
</tr>
</table>
</form>
</main>
<script type="text/javascript">
var flist = [];
var clist = [];
var counter = 0;
function validnum(F) {
if(F < -9999 || F > 9999)
return false;
else
return true;
}
function fNumericCharactersOnly(evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
return (charCode >= 48 && charCode <= 57); // 48 to 57 ==> 0 to 9
}
function convertTemp() {
var c = document.getElementById('ctemp'),
f = document.getElementById('ftemp');
c.value = parseFloat(Math.round((f.value - 32) * 5 / 9)).toFixed(2);
tf = f.value, tc = c.value;
flist.push(tf); clist.push(tc);
var str = "";
str += '\t' + tf + '\t' + '&nbsp' + '&nbsp' + tc + "\n";
document.getElementById("txtArea").innerHTML = str;
}
function averageTemp() {
var content="";
var sumF = 0;
var sumC = 0;
for (var i = 0; i < flist.length; i++) {
content += '\t' + flist[i] + '\t' + '&nbsp' + '&nbsp' + clist[i] + "\n";
sumF += parseInt(flist[i], 10);
sumC += parseInt(clist[i], 10);
}
bars = '===============================';
var avgF = parseFloat(sumF / flist.length).toFixed(2);
var avgC = parseFloat(sumC / clist.length).toFixed(2);
document.getElementById("txtArea").innerHTML = content + bars + "\n" + '\t' + avgF + '\t' + '&nbsp' + '&nbsp' + avgC;
flist = [];
clist = [];
document.getElementById("Avgbtn").disabled=true;
}
function AddResetbutton() {
document.getElementById('ButtonSpot').innerHTML = '<input type="button" onClick="removeButton();" value="Reset" />';
document.getElementById("Convertbtn").disabled=true;
}
function removeButton() {
document.getElementById("myForm").reset();
document.getElementById('ButtonSpot').innerHTML = '';
document.getElementById("txtArea").value = "";
document.getElementById("Convertbtn").disabled=true;
document.getElementById("Avgbtn").disabled=true;
}
</script>
</body>
</html>
Also, I have attempted to make the script automatically display all values after the 10th one is entered, but can't seem to make it work. Any suggestions?
Hey Your code is fixed.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Temperature Conversion</title>
<style type="text/css">
body { font: 1em calibri, arial; }
button {
background-color: transparent;
margin: 5px;
width: 300px;
}
h1, h2, h3, h4 { text-align: center; }
table {
border: 8px double;
margin-left: auto;
margin-right: auto;
padding: 2px;
height: 500px;
width: 30%;
}
td { border: 1px solid; }
td#topcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#midcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#bottomcell { text-align: center; }
textarea {
width: 250px;
height: 250px;
}
p {
word-spacing: 25px;
}
#Fahr {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#Cels {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#ftemp, #ctemp {
display: inline;
float: middle;
}
</style>
</head>
<body>
<main role="main">
<form id="myForm" onsubmit="return this.ftemp.value!=''">
<table>
<tr>
<td id="topcell">
<label for="Fahrenheit" id="Fahr">Fahrenheit:</label><input id="ftemp" onkeypress="return fNumericCharactersOnly(event)" onkeyup="this.form.Convertbtn.disabled = this.value==''; this.form.Avgbtn.disabled = this.value==''; if(!validnum(this.value)) this.value=''">
<br /><br />
<label for="Celsius" id="Cels" >Celsius:</label><input id="ctemp" readonly>
<br /><br /><br /><br /><br /><br />
<p>Fahrenheit Celsius</p>
</td>
</tr>
<tr>
<td id="midcell">
<br />
<textarea rows="5" id="txtArea" name="textarea-name" readonly></textarea>
</td>
</tr>
<tr>
<td id="bottomcell">
<input type="button" id="Convertbtn" value="Convert" accesskey="c" onclick="convertTemp(); counter++" disabled="disabled"/>
<input type="button" id="Avgbtn" value="Average" accesskey="a" onclick="averageTemp(); AddResetbutton()" disabled="disabled"/>
<div id="ButtonSpot"></div>
</td>
</tr>
</table>
</form>
</main>
<script type="text/javascript">
var flist = [];
var clist = [];
var counter = 0;
function validnum(F) {
if(F < -9999 || F > 9999)
return false;
else
return true;
}
function fNumericCharactersOnly(evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
return (charCode >= 48 && charCode <= 57); // 48 to 57 ==> 0 to 9
}
function convertTemp() {
var c = document.getElementById('ctemp'),
f = document.getElementById('ftemp');
c.value = parseFloat(Math.round((f.value - 32) * 5 / 9)).toFixed(2);
tf = f.value, tc = c.value;
flist.push(tf); clist.push(tc);
var str = "";
str += '\t' + tf + '\t' + '&nbsp' + '&nbsp' + tc + "\n";
document.getElementById("txtArea").innerHTML = str;
}
function averageTemp() {
var content="";
var sumF = 0;
var sumC = 0;
for (var i = 0; i < flist.length; i++) {
content += '\t' + flist[i] + '\t' + '&nbsp' + '&nbsp' + clist[i] + "\n";
sumF += parseInt(flist[i], 10);
sumC += parseInt(clist[i], 10);
}
bars = '===============================';
var avgF = parseFloat(sumF / flist.length).toFixed(2);
var avgC = parseFloat(sumC / clist.length).toFixed(2);
document.getElementById("txtArea").innerHTML = content + bars + "\n" + '\t' + avgF + '\t' + '&nbsp' + '&nbsp' + avgC;
flist = [];
clist = [];
document.getElementById("Avgbtn").disabled=true;
}
function AddResetbutton() {
document.getElementById('ButtonSpot').innerHTML = '<input type="button" onClick="removeButton();" value="Reset" />';
document.getElementById("Convertbtn").disabled=true;
}
function removeButton() {
document.getElementById("myForm").reset();
document.getElementById('ButtonSpot').innerHTML = '';
document.getElementById("txtArea").innerHTML = '';
document.getElementById("Convertbtn").disabled=true;
document.getElementById("Avgbtn").disabled=true;
}
</script>
</body>
</html>

Calculator in JavaScript

I can't find a good calculator in JavaScript.
In a first time I was using the eval function on my datas to get my result but there were mistakes.
So I found this code:
function calculate(input){
var f = { add : '+'
, sub : '-'
, div : '/'
, mlt : '*'
, mod : '%'
, exp : '^' };
// Create array for Order of Operation and precedence
f.ooo = [[ [f.mlt] , [f.div] , [f.mod] , [f.exp] ],
[ [f.add] , [f.sub] ]];
input = input.replace(/[^0-9%^*\/()\-+.]/g,''); // clean up unnecessary characters
var output;
for(var i=0, n=f.ooo.length; i<n; i++ ){
// Regular Expression to look for operators between floating numbers or integers
var re = new RegExp('(\\d+\\.?\\d*)([\\'+f.ooo[i].join('\\')+'])(\\d+\\.?\\d*)');
re.lastIndex = 0; // be cautious and reset re start pos
// Loop while there is still calculation for level of precedence
while( re.test(input) ){
//document.write('<div>' + input + '</div>');
output = calc_internal(RegExp.$1,RegExp.$2,RegExp.$3);
if (isNaN(output) || !isFinite(output)) return output; // exit early if not a number
input = input.replace(re,output);
}
}
return output;
function calc_internal(a,op,b){
a=a*1; b=b*1;
switch(op){
case f.add: return a+b; break;
case f.sub: return a-b; break;
case f.div: return a/b; break;
case f.mlt: return a*b; break;
case f.mod: return a%b; break;
case f.exp: return Math.pow(a,b); break;
default: null;
}
}
}
http://jsfiddle.net/vol7ron/6cdfA/
But there are some problems using parenthesis, for example: (10+1)*5 = 11
So I'm trying to find a good calculator in JavaScript to calculate string expressions.
Thanks for your help.
You can use the math.js library, which comes with a powerful expression parser:
http://mathjs.org
I don't have javascript code for it, but general solution how to evaluate complex expresion in string is to convert it using Shunting-yard algorithm into RPN and then use Reverse Polish notation algorithm to get result.
This is a solution i recently come up with as an exercise for using clusure in Javascript.
var PocketCalculator = function() {
var allowedOperators = ["+", "-", "*", "/", "="],
operations = {
"+": function(a, b) {
return a + b;
},
"-": function(a, b) {
return a - b;
},
"*": function(a, b) {
return a * b;
},
"/": function(a, b) {
return a / b;
}
},
cache = 0,
makeOperation = function(b, f) {
return function() {
return cache = f(cache, b);
};
},
prevOperation = operations["+"],
operation = makeOperation(0, prevOperation);
return {
clear: function() {
cache = 0;
prevOperation = operations["+"]
operation = makeOperation(0, prevOperation);
},
push: function(operator, b) {
if (allowedOperators.indexOf(operator) < 0)
return;
if (operator !== "=") {
prevOperation = operations[operator];
operation = makeOperation(b, prevOperation);
} else if (b !== undefined)
operation = makeOperation(b, prevOperation);
return operation();
}
};
};
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
::selection { background-color: #E13300; color: white; }
::-moz-selection { background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body {
margin: 0 15px 0 15px;
}
p.footer {
text-align: right;
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
box-shadow: 0 0 8px #D0D0D0;
}
</style>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".num").click(function(){
var oprator = $("#val2").val();
var one = $(this).val();
if (oprator=='') {
var val1 = $("#val1").val();
$("#val1").val(val1+one);
}else{
var val1 = $("#val3").val();
$("#val3").val(val1+one);
}
});
$(".opt").click(function(){
var plus = $(this).val();
$("#val2").val(plus);
});
$("#equle").click(function(){
var plus = $("#equle").val();
var v1 = $("#val1").val();
var v2 = $("#val2").val();
var v3 = $("#val3").val();
var v1int=parseInt(v1);
var v3int=parseInt(v3);
if (v2=="+") {
var z = v1int+v3int;
}else if(v2=="-"){
var z = v1int-v3int;
}
else if(v2=="*"){
var z = v1int*v3int;
}
else{
var z = v1int/v3int;
}
$("#val4").val(z);
});
});
</script
<body>
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
<div id="body">
<table>
<tr cospan="5">
<td colspan="2"><input type='text' name="val1" value="" id="val1"/></td>
<td colspan="1"><input type='text' name="val2" value="" id="val2"/></td>
<td colspan="1"><input type='text' name="val3" value="" id="val3"/></td>
<td colspan="1"><input type='text' name="val4" value="" id="val4"/></td></tr>
<tr>
<td><button type="button" class="num" id="one" value="1">1</button></td>
<td><button type="button" class="num" id="two" value="2">2</button></td>
<td><button type="button" class="num" id="three" value="3">3</button></td>
<td><button type="button" class="num" id="four" value="4">4</button</td>
<td><button type="button" class="num" id="five" value="5">5</button></td>
</tr>
<tr>
<td><button type="button" class="num" id="six" value="6">6</button></td>
<td><button type="button" class="num" id="seven" value="7">7</button></td>
<td><button type="button" class="num" id="eight" value="8">8</button></td>
<td><button type="button" class="num" id="nine" value="9">9</button></td>
<td><button type="button" class="num" id="ten" value="10">0</button></td>
</tr>
<tr>
<td><button type="button" id="plus" class="opt" value="+">+</button></td>
<td><button type="button" id="minus" class="opt" value="-">-</button></td>
<td><button type="button" id="mul" class="opt" value="*">*</button></td>
<td><button type="button" id="dev" class="opt" value="/">/</button></td>
<td><button type="button" id="equle" value="=">=</button></td>
</tr>
</table>
</div>
</div>
</body>
</html>

Add/Delete table rows dynamically using JavaScript

I'm trying to add/delete table rows following this example and this example.
Here's my code:
HTML Form
<div id="POItablediv">
<input type="button" id="addPOIbutton" value="Add POIs"/><br/><br/>
<table id="POITable" border="1">
<tr>
<td>POI</td>
<td>Latitude</td>
<td>Longitude</td>
<td>Delete?</td>
<td>Add Rows?</td>
</tr>
<tr>
<td>1</td>
<td><input size=25 type="text" id="latbox" readonly=true/></td>
<td><input size=25 type="text" id="lngbox" readonly=true/></td>
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()"/></td>
</tr>
</table>
</div>
JavaScript
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
var x=document.getElementById('POITable').insertRow(1);
var c1=x.insertCell(0);
var c2=x.insertCell(1);
c1.innerHTML="NEW CELL1";
c2.innerHTML="NEW CELL2";
}
Now, as you can see, In my table I have text fields and buttons. What I want:
Just to repeat the structure of the row. I can't do it right now since innerHTM just takes texts. How can I insert a textfield or label?
The ids of the textfields should also be different since I'll retrieve the values later to put it in a database.
I want to put a function to increment the number of POIs as well
Can anyone help me out please?
You could just clone the first row that has the inputs, then get the nested inputs and update their ID to add the row number (and do the same with the first cell).
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
var x=document.getElementById('POITable');
// deep clone the targeted row
var new_row = x.rows[1].cloneNode(true);
// get the total number of rows
var len = x.rows.length;
// set the innerHTML of the first row
new_row.cells[0].innerHTML = len;
// grab the input from the first cell and update its ID and value
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
// grab the input from the first cell and update its ID and value
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
// append the new row to the table
x.appendChild( new_row );
}
Demo below
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow() {
console.log('hi');
var x = document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild(new_row);
}
<div id="POItablediv">
<input type="button" id="addPOIbutton" value="Add POIs" /><br/><br/>
<table id="POITable" border="1">
<tr>
<td>POI</td>
<td>Latitude</td>
<td>Longitude</td>
<td>Delete?</td>
<td>Add Rows?</td>
</tr>
<tr>
<td>1</td>
<td><input size=25 type="text" id="latbox" /></td>
<td><input size=25 type="text" id="lngbox" readonly=true/></td>
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" /></td>
<td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()" /></td>
</tr>
</table>
Easy Javascript Add more Rows with delete functionality
Cheers !
<TABLE id="dataTable">
<tr><td>
<INPUT TYPE=submit name=submit id=button class=btn_medium VALUE=\'Save\' >
<INPUT type="button" value="AddMore" onclick="addRow(\'dataTable\')" class="btn_medium" />
</td></tr>
<TR>
<TD>
<input type="text" size="20" name="values[]"/> <br><small><font color="gray">Enter Title</font></small>
</TD>
</TR>
</table>
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell3 = row.insertCell(0);
cell3.innerHTML = cell3.innerHTML +' <input type="text" size="20" name="values[]"/> <INPUT type="button" class="btn_medium" value="Remove" onclick="this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);" /><br><small><font color="gray">Enter Title</font></small>';
//cell3.innerHTML = cell3.innerHTML +' <input type="text" size="20" name="values[]"/> <INPUT type="button" class="btn_medium" value="Remove" onclick="this.parentNode.parentNode.innerHTML=\'\';" /><br><small><font color="gray">Enter Title</font></small>';
}
</script>
This seems a lot cleaner than the answer above...
<script>
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.innerHTML = x.innerHTML.replace(/{id}/, ++maxID);
return x;
}
function addRow() {
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);
}
</script>
<table id="theTable">
<tr>
<td>id</td>
<td>name</td>
</tr>
<tr id="templateRow" style="display:none">
<td>{id}</td>
<td><input /></td>
</tr>
</table>
<button onclick="addRow();">Go</button>
If you put a delete button on each row, then:
<tr>
<td><input type="button" value="Delete row" onclick="deleteRow(this);">
<td><input type="text">
<td><input type="text">
And the deleteRow function can be:
function deleteRow(el) {
// while there are parents, keep going until reach TR
while (el.parentNode && el.tagName.toLowerCase() != 'tr') {
el = el.parentNode;
}
// If el has a parentNode it must be a TR, so delete it
// Don't delte if only 3 rows left in table
if (el.parentNode && el.parentNode.rows.length > 3) {
el.parentNode.removeChild(el);
}
}
If all your rows have the same content, it will be much faster to add a row by cloning an existing row:
function addRow(tableID) {
var table = document.getElementById(tableID);
if (!table) return;
var newRow = table.rows[1].cloneNode(true);
// Now get the inputs and modify their names
var inputs = newRow.getElementsByTagName('input');
for (var i=0, iLen=inputs.length; i<iLen; i++) {
// Update inputs[i]
}
// Add the new row to the tBody (required for IE)
var tBody = table.tBodies[0];
tBody.insertBefore(newRow, tBody.lastChild);
}
You can add a row to a table in the most easiest way like this :-
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body is the id of the table body tag .
1 & 2: innerHTML can take HTML as well as text. You could do something like:
c1.innerHTML = "<input size=25 type=\"text\" id='newID' readonly=true/>";
May or may not be the best way to do it, but you could do it that way.
3: I would just use a global variable that holds the number of POIs and increment/decrement it each time.
Here Is full code with HTML,CSS and JS.
<style><style id='generate-style-inline-css' type='text/css'>
body {
background-color: #efefef;
color: #3a3a3a;
}
a,
a:visited {
color: #1e73be;
}
a:hover,
a:focus,
a:active {
color: #000000;
}
body .grid-container {
max-width: 1200px;
}
body,
button,
input,
select,
textarea {
font-family: "Open Sans", sans-serif;
}
.entry-content>[class*="wp-block-"]:not(:last-child) {
margin-bottom: 1.5em;
}
.main-navigation .main-nav ul ul li a {
font-size: 14px;
}
#media (max-width:768px) {
.main-title {
font-size: 30px;
}
h1 {
font-size: 30px;
}
h2 {
font-size: 25px;
}
}
.top-bar {
background-color: #636363;
color: #ffffff;
}
.top-bar a,
.top-bar a:visited {
color: #ffffff;
}
.top-bar a:hover {
color: #303030;
}
.site-header {
background-color: #ffffff;
color: #3a3a3a;
}
.site-header a,
.site-header a:visited {
color: #3a3a3a;
}
.main-title a,
.main-title a:hover,
.main-title a:visited {
color: #222222;
}
.site-description {
color: #757575;
}
.main-navigation,
.main-navigation ul ul {
background-color: #222222;
}
.main-navigation .main-nav ul li a,
.menu-toggle {
color: #ffffff;
}
.main-navigation .main-nav ul li:hover>a,
.main-navigation .main-nav ul li:focus>a,
.main-navigation .main-nav ul li.sfHover>a {
color: #ffffff;
background-color: #3f3f3f;
}
button.menu-toggle:hover,
button.menu-toggle:focus,
.main-navigation .mobile-bar-items a,
.main-navigation .mobile-bar-items a:hover,
.main-navigation .mobile-bar-items a:focus {
color: #ffffff;
}
.main-navigation .main-nav ul li[class*="current-menu-"]>a {
color: #ffffff;
background-color: #3f3f3f;
}
.main-navigation .main-nav ul li[class*="current-menu-"]>a:hover,
.main-navigation .main-nav ul li[class*="current-menu-"] .sfHover>a {
color: #ffffff;
background-color: #3f3f3f;
}
.navigation-search input[type="search"],
.navigation-search input[type="search"]:active {
color: #3f3f3f;
background-color: #3f3f3f;
}
.navigation-search input[type="search"]:focus {
color: #ffffff;
background-color: #3f3f3f;
}
.main-navigation ul ul {
background-color: #3f3f3f;
}
.main-navigation .main-nav ul ul li a {
color: #ffffff;
}
.main-navigation .main-nav ul ul li:hover>a,
.main-navigation .main-nav ul ul li:focus>a,
.main-navigation .main-nav ul ul li.sfHover>a {
color: #ffffff;
background-color: #4f4f4f;
}
.main-navigation . main-nav ul ul li[class*="current-menu-"]>a {
color: #ffffff;
background-color: #4f4f4f;
}
.main-navigation .main-nav ul ul li[class*="current-menu-"]>a:hover,
.main-navigation .main-nav ul ul li[class*="current-menu-"] .sfHover>a {
color: #ffffff;
background-color: #4f4f4f;
}
.separate-containers .inside-article,
.separate-containers .comments-area,
.separate-containers .page-header,
.one-container .container,
.separate-containers .paging-navigation,
.inside-page-header {
background-color: #ffffff;
}
.entry-meta {
color: #595959;
}
.entry-meta a,
.entry-meta a:visited {
color: #595959;
}
.entry-meta a:hover {
color: #1e73be;
}
.sidebar .widget {
background-color: #ffffff;
}
.sidebar .widget .widget-title {
color: #000000;
}
.footer-widgets {
background-color: #ffffff;
}
.footer-widgets .widget-title {
color: #000000;
}
.site-info {
color: #ffffff;
background-color: #222222;
}
.site-info a,
.site-info a:visited {
color: #ffffff;
}
.site-info a:hover {
color: #606060;
}
.footer-bar .widget_nav_menu .current-menu-item a {
color: #606060;
}
input[type="text"],
input[type="email"],
input[type="url"],
input[type="password"],
input[type="search"],
input[type="tel"],
input[type="number"],
textarea,
select {
color: #666666;
background-color: #fafafa;
border-color: #cccccc;
}
input[type="text"]:focus,
input[type="email"]:focus,
input[type="url"]:focus,
input[type="password"]:focus,
input[type="search"]:focus,
input[type="tel"]:focus,
input[type="number"]:focus,
textarea:focus,
select:focus {
color: #666666;
background-color: #ffffff;
border-color: #bfbfbf;
}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"],
a.button,
a.button:visited,
a.wp-block-button__link:not(.has-background) {
color: #ffffff;
background-color: #666666;
}
button:hover,
html input[type="button"]:hover,
input[type="reset"]:hover,
input[type="submit"]:hover,
a.button:hover,
button:focus,
html input[type="button"]:focus,
input[type="reset"]:focus,
input[type="submit"]:focus,
a.button:focus,
a.wp-block-button__link:not(.has-background):active,
a.wp-block-button__link:not(.has-background):focus,
a.wp-block-button__link:not(.has-background):hover {
color: #ffffff;
background-color: #3f3f3f;
}
.generate-back-to-top,
.generate-back-to-top:visited {
background-color: rgba( 0, 0, 0, 0.4);
color: #ffffff;
}
.generate-back-to-top:hover,
.generate-back-to-top:focus {
background-color: rgba( 0, 0, 0, 0.6);
color: #ffffff;
}
.entry-content .alignwide,
body:not(.no-sidebar) .entry-content .alignfull {
margin-left: -40px;
width: calc(100% + 80px);
max-width: calc(100% + 80px);
}
#media (max-width:768px) {
.separate-containers .inside-article,
.separate-containers .comments-area,
.separate-containers .page-header,
.separate-containers .paging-navigation,
.one-container .site-content,
.inside-page-header {
padding: 30px;
}
.entry-content .alignwide,
body:not(.no-sidebar) .entry-content .alignfull {
margin-left: -30px;
width: calc(100% + 60px);
max-width: calc(100% + 60px);
}
}
.rtl .menu-item-has-children .dropdown-menu-toggle {
padding-left: 20px;
}
.rtl .main-navigation .main-nav ul li.menu-item-has-children>a {
padding-right: 20px;
}
.one-container .sidebar .widget {
padding: 0px;
}
.append_row {
color: black !important;
background-color: #FFD6D6 !important;
border: 1px #ccc solid !important;
}
.append_column {
color: black !important;
background-color: #D6FFD6 !important;
border: 1px #ccc solid !important;
}
table#my-table td {
width: 50px;
height: 27px;
border: 1px solid #D3D3D3;
text-align: center;
padding: 0;
}
div#my-container input {
padding: 5px;
font-size: 12px !important;
width: 100px;
margin: 2px;
}
.row {
background-color: #FFD6D6 !important;
}
.col {
background-color: #D6FFD6 !important;
}
</style>
<script src="https://code.jquery.com/jquery-1.11.0.js"></script>
<script>
// append row to the HTML table
function appendRow() {
var tbl = document.getElementById('my-table'), // table reference
row = tbl.insertRow(tbl.rows.length), // append table row
i;
// insert table cells to the new row
for (i = 0; i < tbl.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
// create DIV element and append to the table cell
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode(text); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('class', style); // set DIV class attribute
div.setAttribute('className', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
// append column to the HTML table
function appendColumn() {
var tbl = document.getElementById('my-table'), // table reference
i;
// open loop for each row and append cell
for (i = 0; i < tbl.rows.length; i++) {
createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
}
}
// delete table rows with index greater then 0
function deleteRows() {
var tbl = document.getElementById('my-table'), // table reference
lastRow = tbl.rows.length - 1, // set the last row index
i;
// delete rows with index greater then 0
for (i = lastRow; i > 0; i--) {
tbl.deleteRow(i);
}
}
// delete table columns with index greater then 0
function deleteColumns() {
var tbl = document.getElementById('my-table'), // table reference
lastCol = tbl.rows[0].cells.length - 1, // set the last column index
i, j;
// delete cells with index greater then 0 (for each row)
for (i = 0; i < tbl.rows.length; i++) {
for (j = lastCol; j > 0; j--) {
tbl.rows[i].deleteCell(j);
}
}
}
</script>
<div id="my-container">
<center><br>
<input type="button" value="Add row" onclick="javascript:appendRow()" class="append_row"><br>
<input type="button" value="Add column" onclick="javascript:appendColumn()" class="append_column"><br>
<input type="button" value="Delete rows" onclick="javascript:deleteRows()" class="delete"><br>
<input type="button" value="Delete columns" onclick="javascript:deleteColumns()" class="delete"><br>
<input type="button" value="Delete both" onclick="javascript:deleteColumns();deleteRows()" class="delete"><p></p>
<table id="my-table" align="center" cellspacing="0" cellpadding="0" border="0">
<tbody><tr>
<td>Small</td>
</tr>
</tbody></table>
<p></p></center>
</div>
Add or Delete row(s) dynamically!
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<style type="text/css">
.democlass{
color:red;
}
</style>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var row = table.insertRow(rowCount);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
row = table.insertRow(table.rows.length);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
row = table.insertRow(table.rows.length);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[2].cells[i].innerHTML;
}
row = table.insertRow(table.rows.length);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type=\"button\" value=\"Delete Row\" onclick=\"removeRow(this)\"/>";
} else {
newcell.innerHTML = table.rows[3].cells[i].innerHTML;
}
}
}
/**
* This method deletes the specified section of the table
* OR deletes the specified rows from the table.
*/
function removeRow(src) {
var oRow = src.parentElement.parentElement;
var rowsCount = 0;
for(var index = oRow.rowIndex; index >= 0; index--) {
document.getElementById("dataTable").deleteRow(index);
if(rowsCount == (4 - 1)) {
return;
}
rowsCount++;
}
//once the row reference is obtained, delete it passing in its rowIndex
/* document.getElementById("dataTable").deleteRow(oRow.rowIndex); */
}
</SCRIPT>
</HEAD>
<BODY>
<form name="myForm">
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD>
<INPUT type="checkbox" name="chk"/>
</TD>
<TD>
Code
</TD>
<TD>
<INPUT type="text" name="txt"/>
</TD>
<TD>
Select Country
</TD>
<TD>
<SELECT name="country">
<OPTION value="in">India</OPTION>
<OPTION value="de">Germany</OPTION>
<OPTION value="fr">France</OPTION>
<OPTION value="us">United States</OPTION>
<OPTION value="ch">Switzerland</OPTION>
</SELECT>
</TD>
</TR>
<TR>
<TD> </TD>
<TD>
First Name
</TD>
<TD>
<INPUT type="text" name="txt1"/>
</TD>
<TD>
Last Name
</TD>
<TD>
<INPUT type="text" name="txt2"/>
</TD>
</TR>
<TR>
<TD> </TD>
<TD>Phone</TD>
<TD>
<INPUT type="text" name="txt3"/>
</TD>
<TD>Address</TD>
<TD>
<INPUT type="text" name="txt4" class="democlass"/>
</TD>
</TR>
<TR>
<TD> </TD>
<TD> </TD>
<TD>
</TD>
<TD> </TD>
<TD>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
I used some of the solutions indicated above plus solutions from other postings to come up with a working solution for a dynamic table containing input fields. I'm doing this because it might help someone who finds this thread after searching for the same things that led me to it, and also because the accepted answer (and associated jsfiddle) doesn't actually work! That is, it doesn't index the table rows correctly after a number of inserts/deletes. The key issue is how to uniquely index the dynamic row data, which is possible with a bit of jquery:
<form id=frmLines>
<table id=tabLines>
<tr>
<td>img src='/some/suitable/graphic' onclick='removeLine(this);'/></td>
<td><input type='text' name='field1' /></td>
<td><input type='text' name='field2' /></td>
<td><input type='text' name='field3' /></td>
</tr>
<tr>
<td><img src='/some/suitable/graphic' onclick='addLine();' /></td>
<td colspan=3> </td>
</tr>
</table>
</form>
Note the form and table have id's for direct DOM referencing, but you can't use id's on the input fields as to make them unique you'd need to introduce an index which would massively complicate the code - and its easy enough to access them by name when the form is processed (see below)
Then the javascript to control adding and removing lines is like this:
function addLine() {
var tabLines = document.getElementById("tabLines");
var tabLinesRow = tabLines.insertRow(tabLines.rows.length-1);
var col1html = "<img src='/some/suitable/graphic' onclick='removeLine(this);'>";
var col2html = "<input type='text' name='field1' />";
var col3html = "<input type='text' name='field2' />";
var col4html = "<input type='text' name='field3' />";
var col1 = tabLinesRow.insertCell(0); col1.innerHTML=col1html;
var col2 = tabLinesRow.insertCell(1); col2.innerHTML=col2html;
var col3 = tabLinesRow.insertCell(2); col3.innerHTML=col3html;
var col4 = tabLinesRow.insertCell(3); col4.innerHTML=col4html;
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
Then the final part of the jigsaw - the javascript to process the form data when its submitted. The key jquery function here is .eq() - which allows you to access the field names in the order they appear in the form - i.e. in table row order.
var frmData = {}; // an object to contain all form data
var arrLines = new Array(); // array to contain the dynamic lines
var tabLines = document.getElementById("tabLines").rows.length-1;
for (i=0;i<tabLines;i++) {
arrLines[i] = {};
arrLines[i]['no'] = i+1;
arrLines[i]['field1'] = $("#frmLines input[name=field1]").eq(i).val();
arrLines[i]['field2'] = $("#frmLines input[name=field2]").eq(i).val();
arrLines[i]['field3'] = $("#frmLines input[name=field3]").eq(i).val();
}
frmData['lines'] = arrLines;
frmData['another_field'] = $('#frmLines input[name=another_field]").val();
var jsonData = JSON.stringify(frmData);
// lines of data now in a JSON structure as indexed array
// (plus other fields in the JSON as required)
// ready to post via ajax etc
I hope this helps someone, either directly or indirectly. There are a couple of subtle techniques being used which aren't that complicated but took me 3-4 hours to piece together.
Javascript dynamically adding table data.
SCRIPT
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1); // •No Of Columns to be Validated on Text.
for(var j = 0; j < colCount; j++) {
var text = window.document.getElementById('input'+j).value;
if (j == validate_Noof_columns) {
row = table.insertRow(2); // •location of new row.
for(var i = 0; i < colCount; i++) {
var text = window.document.getElementById('input'+i).value;
var newcell = row.insertCell(i);
if(i == (colCount - 1)) { // Replace last column with delete button
newcell.innerHTML = "<INPUT type='button' value='X' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
window.document.getElementById('input'+i).value = '';
}
}
}else if (text != 'undefined' && text.trim() == ''){
alert('input'+j+' is EMPTY');break;
}
}
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
HTMl
<div align='center'>
<TABLE id='dataTable' border='1' >
<TBODY>
<TR><th align='center'><b>First Name:</b></th>
<th align='center' colspan='2'><b>Last Name:</b></th>
<th></th>
</TR>
<TR><TD ><INPUT id='input0' type="text"/></TD>
<TD ><INPUT id='input1' type='text'/></TD>
<TD>
<INPUT type='button' id='input2' value='+' onclick="addRow('dataTable')" />
</TD>
</TR>
</TBODY>
</TABLE>
</div>
Example : jsfiddle

Categories

Resources