Javascript-Using single function instead of multiple - javascript

Here the code:
<script type="text/javascript">
function ChangeColor1()
{
t1.style.backgroundColor = 'pink';
t2.style.backgroundColor = '';
t3.style.backgroundColor = '';
}
function ChangeColor2()
{
t1.style.backgroundColor = '';
t2.style.backgroundColor = 'pink';
t3.style.backgroundColor = '';
}
function ChangeColor3()
{
t1.style.backgroundColor = '';
t2.style.backgroundColor = '';
t3.style.backgroundColor = 'pink';
}
</script>
</head>
<body>
<table width="50%" border="1" >
<tr id="t1" onclick="ChangeColor1();">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr id="t2" onclick="ChangeColor2();">
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr id="t3" onclick="ChangeColor3();">
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
</body>
In this program there are 3 functions are used. I want to do this task using a single function instead of one.

function changeColor(n){
t1.style.backgroundColor = n == 1 ? 'pink' : '';
t2.style.backgroundColor = n == 2 ? 'pink' : '';
t3.style.backgroundColor = n == 3 ? 'pink' : '';
}
... onclick="changeColor(1)" ...
Would be how I'd refactor it. Or better yet make an array of var ts = [t1,t2,t3] then reference ts[n].
var ts = [t1,t2,t3];
function changeColor(n){
for (var i = 0; i < ts.length; i++){
ts[i].style.backgroundColor = (i+1) == n ? 'pink' : '';
}
}
Or you can reference the id directly:
function changeColor(n){
for (var i = 1; i < 4; i++){
document.getElementById('t'+i).style.backgroundColor = n == i ? 'pink' : '';
}
}
You can also take it a step farther and reference the row itself instead of specifying the index as an argument (keeping it generic):
function changeColor(t){
for (var n = 1; n < 4; n++){
var tn = document.getElementById('t'+n);
tn.style.backgroundColor = tn.id == t.id ? 'pink' : '';
}
}
... onclick="changeColor(this);" ...

DEMO
NOTE: Not all browsers will accept t1.style without the document.getElementById
function ChangeColor(row) {
var idx=row.id;
for (var i=1;i<=3;i++) {
document.getElementById("t"+i).style.backgroundColor = (idx==="t"+i)?"pink":"";
}
}
using
<tr id="t1" onclick="ChangeColor(this);">
<tr id="t2" onclick="ChangeColor(this);">
<tr id="t3" onclick="ChangeColor(this);">

Related

For loop inside for loop not working properly repeating same values multiple times Javascript

I'm wanting every <tbody> tag will be gone as object index like first <tbody>->1 and second <tbody>-> 2 then inside the <tbody> every <tr> will be another object and that will be store into the <tbody> object and last the last part every <td> should have object key ("eiin", "name") inside the <tr> object
I'm trying using for loop multiple times but the console.log showing me okay but first object repeated 2 times.
Html
<section class="institute_list">
<table class="table" border="1">
<thead>
<tr>
<th scope="col">EIIN</th>
<th scope="col">Institute</th>
</tr>
</thead>
<tbody>
<tr>
<td>000000</td>
<td>Name</td>
</tr>
</tbody>
<tbody>
<tr>
<td>111111</td>
<td>Name 2</td>
</tr>
</tbody>
</table>
</section>
Javascript & jQuery
<script>
var rows = '', the_row='', the_xrow={}, tr_values={}, xtd_obj={};
tbodys = ($(".institute_list .table tbody").length);
for( var x=0; tbodys > x; x++) {
rows = $('.institute_list .table tbody:nth-child('+(x+1)+') tr').length;
the_row = '.institute_list .table tbody:nth-child('+(x+1)+') tr:nth-child(';
for( var i=1; rows >= i; i++ ){
tr_values = {
'eiin' : $(the_row+i+') td:first-child').text(),
'name' : $(the_row+i+') td:nth-child(2)').text()
};
the_xrow[i] = tr_values;
}
xtd_obj[x] = the_xrow;
}
console.log(xtd_obj);
</script>
and i'm getting this output in console
here
You may try the code below. You can separate every <tbody>,<tr>,<td> tag as a loop then make them a array.
var target = $(".institute_list > table");
var output = [];
$(target).find("tbody").each(function(i){
output[i] = {};
$(this).children().each(function(j){
output[i][j] = {};
$(this).children().each(function(k, td){
if ( k == 0 ) {
output[i][j]["eiin"] = $(td).text();
} else if ( k == 1 ) {
output[i][j]["name"] = $(td).text();
} else {
output[i][j][k] = $(td).text();
}
});
});
});
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="institute_list">
<table class="table" border="1">
<thead>
<tr>
<th scope="col">EIIN</th>
<th scope="col">Institute</th>
</tr>
</thead>
<tbody>
<tr>
<td>000000</td>
<td>Name</td>
</tr>
</tbody>
<tbody>
<tr>
<td>111111</td>
<td>Name 2</td>
</tr>
</tbody>
</table>
</section>
First, you need a closing </tbody> tag around the first element. Second I think you might be running into a scoping problem. You are defining the_xrow and tr_values outside of the for loops instead of inside of the for loops.
<script>
var xtd_obj={};
var tbodys = ($(".institute_list .table tbody").length);
for( var x=1; tbodys >= x; x++) {
var current_row = '.institute_list .table tbody:nth-child('+x+') tr';
var rows = $(current_row).length;
var the_row = current_row + ':nth-child(';
var the_xrow = {};
for( var i=1; rows >= i; i++ ){
the_xrow[i] = {
'eiin' : $(the_row+i+') td:first-child').text(),
'name' : $(the_row+i+') td:nth-child(2)').text()
};
}
xtd_obj[x] = the_xrow;
}
console.log(xtd_obj);
</script>
It's working for me
<script>
var rows = '', the_row='', xtd_obj={};
var tbodys = ($(".institute_list .table tbody").length)+1;
for( var x=1; tbodys > x; x++) {
rows = $('.institute_list .table tbody:nth-child('+(x+1)+') tr').length;
the_row = '.institute_list .table tbody:nth-child('+(x+1)+') tr:nth-child(';
var the_xrow = {};
for( var i=0; rows > i; i++ ){
var tr_values = {
'eiin' : $(the_row+i+1+') td:first-child').text(),
'name' : $(the_row+i+1+') td:nth-child(2)').text()
};
the_xrow[i] = tr_values;
}
xtd_obj[x] = the_xrow;
}
console.log(xtd_obj);
</script>
Here's the screenshot

How to highlight a table row with the smallest value in a certain column using javascript

Supposed that I have a table like this on a webpage with the id ='table':
Name Age Money(USD) DATE
A 19 4 2019-03-11 16:15:35
B 20 0 2019-03-11 16:16:37
C 27 3 2019-03-13 04:15:43
D 34 0 2019-03-13 04:16:57
Could you help me find the FIRST SMALLEST VALUE IN THE MONEY COLUMN, which is 0 for B in the Column1 and HIGHLIGHT the whole table row for B, using javascript without using any library and any button onClicking?
Note: I have searched around and just been unlucky enough to find the correct answer to my problem.
Thanks.
UPDATE:I just got a piece of javacript like this to get the first smallest value and print it out, but not be able to highlight the whole row with it
var table = document.getElementById("table"), minVal;
for(var i = 1; i < table.rows.length; i++)
{
// if its the first row get the value
if(i === 1){minVal = table.rows[i].cells[2].innerHTML; }
// test with the other values
else if(minVal > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2].innerHTML;
}
}
document.getElementById("val").innerHTML = " Minimum Value = "+minVal;
console.log(maxVal);
var table = document.getElementById("table"), minVal, minI;
for(var i = 1; i < table.rows.length; i++){
if(i === 1){
minVal = table.rows[i].cells[2].innerHTML;
}
else if(minVal > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2].innerHTML;
minI = i;
}
}
table.rows[i].cells[2].innerHTML = '<span style="background:red">' + table.rows[minI].cells[2].innerHTML + '</span>';
Something like that.
var table = document.getElementById("table");
var minVal = undefined;
for(var i = 1; i < table.rows.length; i++)
{
if(i === 1){
minVal = table.rows[i].cells[2];
}
else if(minVal.innerHTML > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2];
}
}
minVal.parentElement.style.background="yellow";
There are two things you need to do:
Convert innerHTML to a number using +
Keep track of the row number while looping.
This is the code
var table = document.getElementById("table"), minVal;
let minRow = 1;
for(var i = 1; i < table.rows.length; i++)
{
// if its the first row get the value
if(i === 1){
minVal = +table.rows[i].cells[2].innerHTML;
}
// test with the other values
else if(minVal > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2].innerHTML;
minRow = i;
}
}
let row = table.rows[minRow];
row.style.backgroundColor = 'red';
This simply keeps track of the minimum row, and lets you hang your formatting off of that:
const highlightLowest = () => {
var rows = table.rows;
var minRow = rows[0]
for (var i = 1; i < rows.length; i++){
rows[i].classList.remove('highlight')
if (Number(rows[i].cells[2].innerHTML) < Number(minRow.cells[2].innerHTML)) {
minRow = rows[i]
}
}
minRow.classList.add('highlight')
}
tr.highlight td {background-color: yellow}
<table id="table">
<tr><td>A</td><td>19</td><td>4</td><td>2019-03-11 16:15:35</td></tr>
<tr><td>B</td><td>20</td><td>0</td><td>2019-03-11 16:16:37</td></tr>
<tr><td>C</td><td>27</td><td>3</td><td>2019-03-13 04:15:43</td></tr>
<tr><td>D</td><td>34</td><td>0</td><td>2019-03-13 04:16:57</td></tr>
</table>
<hr />
<button onClick="highlightLowest()">Highlight</button>
Here you go. The function 'highlight' takes the column that you want to base your highlighting upon as an argument.
// Get your table's headers
headers = document.querySelectorAll('#table tbody tr th')
// Get your table's headers
rows = document.querySelectorAll('#table tbody tr')
// Declaring function that takes wanted column as argument
highlight = (colName) =>{
let min = 0;
for(i=0;i<headers.length;i++){
if(headers[i].innerText == colName){
for(j=1;j<rows.length;j++){
value = parseInt(rows[j].children[i].innerHTML);
if(j == 1){
min = value;
}
if(value < min){
rows[j].style.backgroundColor = "yellow"
break;
}
}
}
}
}
<table id="table">
<tbody><tr>
<th>Test 1</th>
<th>Test 2</th>
<th>Test 3</th>
</tr>
<tr>
<td>7</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>5</td>
<td>5</td>
</tr>
<tr>
<td>12</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>15</td>
<td>89</td>
<td>4</td>
</tr>
<tr>
<td>3</td>
<td>6</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>8</td>
</tr>
</tbody></table>
<input type='text' id='col'>
<button onclick=highlight(document.getElementById('col').value)>Highlight based on input column</button>

Bundle of onclick() function, Change with Event listener

In the html below, there are many many onclick() function, which i want to change it to eventlistner. I am new to web Programming, previously working with onlick(), But w3 standards has change to event listener. Any Help is greatly appriciated. i want to change onlick() with event listener.
Html:
<p>
<button onclick="window.location.reload()">New Game</button>
</p>
<table class="boxes" >
<tr>
<td id="0" class="BoxCell" onclick="clickCell(this)">1</td>
<td id="1" class="BoxCell" onclick="clickCell(this)">2</td>
</tr>
<tr>
<td id="2" class="BoxCell" onclick="clickCell(this)">3</td>
<td id="3" class="BoxCell" onclick="clickCell(this)">4</td>
</tr>
<tr>
<td id="4" class="BoxCell" onclick="clickCell(this)">5</td>
<td id="5" class="BoxCell" onclick="clickCell(this)">6</td>
</tr>
<tr>
<td id="6" class="BoxCell" onclick="clickCell(this)">7</td>
<td id="7" class="BoxCell" onclick="clickCell(this)">8</td>
</tr>
</table>
JS :
var id_empty;
var num_moves;
var isCompleted = false;
var nums = [1,2,3,4,5,6,7,8];
function startPuzzle() {
num_moves = 0;
isCompleted = false;
for(var i=0; i < 8; i++) {
var tmp = document.getElementById(i);
tmp.className = "BoxCell ";
}
randomNumber = nums.sort(function () { return (Math.round(Math.random())-0.5);});
while(!Problem.prototype.is_solvable(randomNumber)) {
randomNumber = nums.sort(function () { return (Math.round(Math.random())-0.5);});
}
for(var i=0; i < 8; i++) {
var tmp = document.getElementById(i);
if(randomNumber[i] == 8) {
tmp.className = "cell empty";
tmp.innerHTML = "";
id_empty = i;
}
else
tmp.innerHTML = randomNumber[i];
}
}
function clickCell(x)
{
if(isCompleted)
return;
if(x.id != id_empty+'') {
var emptyI = Math.floor(id_empty/2);
var emptyJ = id_empty % 2;
var id_selected = Number(x.id);
var selectedI = Math.floor(id_selected/2);
var selectedJ = id_selected % 2;
if((Math.abs(emptyI - selectedI) == 1 && emptyJ == selectedJ) ||
(Math.abs(emptyJ - selectedJ) == 1 && emptyI == selectedI)) {
document.getElementById(id_empty).className = "BoxCell";
document.getElementById(id_empty).innerHTML = x.innerHTML;
x.className = "cell empty";
x.innerHTML = '';
id_empty = id_selected;
num_moves++;
document.getElementById("moves").innerHTML = "Moves so far: " + num_moves;
if(isDone()){
isCompleted = true;
document.getElementById("moves").innerHTML = "CONGRATS! Number of moves it took to complete: " + num_moves;
}
}
}
}
function isDone() {
return document.getElementById('0').innerHTML == '1' &&
document.getElementById('1').innerHTML == '2' &&
document.getElementById('2').innerHTML == '3' &&
document.getElementById('3').innerHTML == '4' &&
document.getElementById('4').innerHTML == '5' &&
document.getElementById('5').innerHTML == '6' &&
document.getElementById('6').innerHTML == '7';
}
function lastClick() {
var curr_state = currentState();
var problem = new Problem(curr_state);
var sol = Solver.a_star_search(problem);
var result = "<ol>";
for(var i = 0; i < sol.length; i++) {
var n = moveNumb(sol[i],curr_state);
curr_state = problem.result(sol[i],curr_state);
result += "<li>move " + n + "</li>";
}
result += "</ol>";
document.getElementById("steps").innerHTML = result;
}
function currentState() {
var result = [];
for(var i = 0; i < 8; i++) {
var tmp = document.getElementById(String(i)).innerHTML;
if(tmp == '') {
result[i] = 8;
}
else {
result[i] = Number(tmp);
}
}
return result;
}
function moveNumb(action,state) {
var i = state.indexOf(8);
switch(action) {
case Action.up:
return state[Util.index(Util.x(i),Util.y(i) - 1)];
case Action.down:
return state[Util.index(Util.x(i),Util.y(i) + 1)];
case Action.right:
return state[Util.index(Util.x(i) + 1,Util.y(i))];
case Action.left:
return state[Util.index(Util.x(i) - 1,Util.y(i))];
}
}
Array.prototype.clone = function() { return this.slice(0); };
Array.prototype.swap = function(i1,i2) {
var copy = this.clone();
var tmp = copy[i1];
copy[i1] = copy[i2];
copy[i2] = tmp;
return copy;
};
var Problem = function(start_state) {
this.init_state = start_state;
return this;
}
Problem.prototype.is_solvable = function(start) {
start = start.clone();
start.splice(start.indexOf(8), 1);
start[7] = 8;
var count = 0;
for(var i = 0; i < 7; i++) {
if(start[i] != i+1) {
count++;
var j = start.indexOf(i+1);
start[j] = start[i];
start[i] = i+1;
}
}
return count % 2 == 0;
}
For the cells part you could attach the click event to the class BoxCell like :
var box_cell = document.getElementsByClassName("BoxCell");
var clickCell = function() {
console.log(this.id);
}
for (var i = 0; i < box_cell.length; i++) {
box_cell[i].addEventListener('click', clickCell, false);
}
For the button it could be :
document.querySelector("#btnReload").addEventListener("click", function(){
window.location.reload();
});
Hope this helps.
var box_cell = document.getElementsByClassName("BoxCell");
var clickCell = function() {
console.log(this.id);
};
for (var i = 0; i < box_cell.length; i++) {
box_cell[i].addEventListener('click', clickCell, false);
}
<table class="boxes">
<tr>
<td id="0" class="BoxCell">1</td>
<td id="1" class="BoxCell">2</td>
</tr>
<tr>
<td id="2" class="BoxCell">3</td>
<td id="3" class="BoxCell">4</td>
</tr>
<tr>
<td id="4" class="BoxCell">5</td>
<td id="5" class="BoxCell">6</td>
</tr>
<tr>
<td id="6" class="BoxCell">7</td>
<td id="7" class="BoxCell">8</td>
</tr>
</table>
I haven't gone through your entire code, but you can do like the following:
On window load, you can loop through the td elements and attach click event listeners like: (Also included click event for New Game button - I assigned id - btnReload to the button).
window.onload = function () {
for (i = 0; i <= 7; i++) {
document.getElementById(i).addEventListener("click", function (e) {
clickCell(e);
})
}
document.getElementById("btnReload").addEventListener("click", function(){
window.location.reload();
})
}
Your clickCell can be changed like this:
function clickCell(e) {
var x = e.target.id;
console.log(x);
//reset of your code
}
Example:
window.onload = function () {
for (i = 0; i <= 7; i++) {
document.getElementById(i).addEventListener("click", function (e) {
clickCell(e);
})
}
document.getElementById("btnReload").addEventListener("click", function(){
window.location.reload();
})
}
function clickCell(e) {
var x = e.target.id;
console.log(x);
//reset of your code
}
<h2>Puzzle Game</h2>
<p id="moves"></p>
<p>
<button id="btnReload">New Game</button>
</p>
<p>
</p>
<table class="boxes">
<tr>
<td id="0" class="BoxCell">1</td>
<td id="1" class="BoxCell">2</td>
</tr>
<tr>
<td id="2" class="BoxCell">3</td>
<td id="3" class="BoxCell">4</td>
</tr>
<tr>
<td id="4" class="BoxCell">5</td>
<td id="5" class="BoxCell">6</td>
</tr>
<tr>
<td id="6" class="BoxCell">7</td>
<td id="7" class="BoxCell">8</td>
</tr>
</table>
Use jquery on( 'click' ,function());
Thats even better in terms of execution

Compare participants in one column of the table and make sum from other column, js

I have a table. I'd like to compare participants. If participant have several result points in the table, the script has to return sum of all participant's results. And so on for every participant.
The table is generated from database (".$row["pnt"]."".$row["station"]."".$row["res"]."):
Participant Station Points
aa Some1 1
dd Some1 2
aa sm2 3
dd sm2 4
bb sm3 5
ee sm3 6
For example I've to recieve such a new table:
aa - 4,
dd - 6,
bb - 5,
ee - 6
I've tried to do so:
$(document).ready(function () {
$("body").click(function () {
var rows = $("tbody tr");
var jo = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 1; j <= rows.length; j++) {
var pnt1 = $(rows[i]).find(".pnt").html();
var stations1 = $(rows[i]).find(".station").html();
var pntR1 = $(rows[i]).find(".res").html();
if (pnt1 == $(rows[j]).find(".pnt").html()) {
pntR1 = parseInt(pntR1);
pntR2 = parseInt($(rows[j]).find(".res").html());
jo.push(pnt1, pntR1, pntR2);
break;
}
}
}
console.log(jo);
});
});
But I understood that I'm on a wrong way. Please, help me. I really appreicate if some one could help me on this issue.
Updated after comments:
<table id="pntsRes">
<thead>
<tr>
<th>Участники</th>
<th>Баллы</th>
</tr>
</thead>
<tbody>
<tr><td class="pnt">aa</td><td class="station">AES</td><td class="res">1</td></tr><tr><td class="pnt">dd</td><td class="station">AES</td><td class="res">2</td></tr>
<tr><td class="pnt">aa</td><td class="station">Science</td><td class="res">3</td></tr>
<tr><td class="pnt">dd</td><td class="station">Science</td><td class="res">4</td></tr><tr><td class="pnt">bb</td><td class="station">Аэродром</td><td class="res">5</td></tr>
<tr><td class="pnt">ee</td><td class="station">aeroport</td><td class="res">6</td></tr></tbody>
</table>
First, I would consider breaking your solution into three functions - one to extract the data from the HTML (which is a questionable practice in itself), one to transform the data, and one to output the new table. This way, your code is much more maintainable.
function getData() {
var rows = $("tbody tr");
var data = [];
rows.each(function(idx, row){
var pnt = row.find('.pnt').html(),
station = row.find('.station').html()),
res = parseInt(row.find('.res').html());
data.push(pnt, station, res);
});
}
Then I would consider something like this for the second method
// Pass the output from getData() into processData()
function processData(data){
var groupedKeys = {};
var groupedData = data.map(function(datum){
var name = datum[0];
var value = datum[2];
groupedKeys[name] = (groupedKeys[name] || 0) + (value || 0);
});
var transformedData = [];
Object.keys(groupedKeys).forEach(function(key){
transformedData.push([key, groupedKeys[key]]);
});
return transformedData;
}
The last method of course would need to be implemented by yourself, there's a ton that could be improved here, but it could be a good start.
I used an associative array (which is just an object in JavaScript) shown below:
http://jsfiddle.net/a5k6w300/
Changes I made:
var jo = [];
changed to an object instead of an array
var jo = {};
I also added the if(isNaN(object[key]) inside the inner loop in order to make sure that these didn't show as NaN as I continued adding them together.
$(document).ready(function () {
$("body").click(function () {
var rows = $("tbody tr");
var jo = {};
console.log(rows);
for (var i = 0; i < rows.length; i++) {
for (var j = 1; j <= rows.length; j++) {
var pnt1 = $(rows[i]).find(".pnt").html();
var stations1 = $(rows[i]).find(".station").html();
var pntR1 = $(rows[i]).find(".res").html();
if (pnt1 == $(rows[j]).find(".pnt").html()) {
pntR1 = parseInt(pntR1);
pntR2 = parseInt($(rows[j]).find(".res").html());
if(isNaN(jo[pnt1])){
jo[pnt1] = 0;
}
jo[pnt1] += pntR1;
break;
}
}
}
console.log(jo);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="pntsRes">
<thead>
<tr>
<th>Участники</th>
<th>Баллы</th>
</tr>
</thead>
<tbody>
<tr>
<td class="pnt">aa</td>
<td class="station">AES</td>
<td class="res">1</td>
</tr>
<tr>
<td class="pnt">dd</td>
<td class="station">AES</td>
<td class="res">2</td>
</tr>
<tr>
<td class="pnt">aa</td>
<td class="station">Science</td>
<td class="res">3</td>
</tr>
<tr>
<td class="pnt">dd</td>
<td class="station">Science</td>
<td class="res">4</td>
</tr>
<tr>
<td class="pnt">bb</td>
<td class="station">Аэродром</td>
<td class="res">5</td>
</tr>
<tr>
<td class="pnt">ee</td>
<td class="station">aeroport</td>
<td class="res">6</td>
</tr>
</tbody>
</table>

Loop through html cells and perform a function if conditionals are met

var tableBody = document.getElementById("firstTableBody"),
secondTable = document.getElementById("secondTable");
function insertRow() {
var Row = tableBody.insertRow();
for (var c = 0; c < 3; c += 1) {
Row.insertCell(c);
}
var Fruits = ["Apples", "Oranges", "Strawberries"],
random_Fruits = Fruits[Math.floor(Math.random() * Fruits.length)];
Row.cells[0].innerHTML = random_Fruits;
Row.cells[1].innerHTML = 100;
var Sellbtn = document.createElement('button');
Sellbtn.innerHTML = "Sell"
Sellbtn.onclick = function Sell() {
if (secondTable.rows.length < 1) {
var Row = secondTable.insertRow();
for (var f = 0; f < 2; f += 1) {
Row.insertCell(f);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
} else {
for (var i = 0; i < secondTable.rows.length; i += 1) {
if (secondTable.rows[i].cells[0].innerHTML === this.parentNode.parentNode.cells[0].innerHTML) {
secondTable.rows[i].cells[1].innerHTML = +this.parentNode.parentNode.cells[1].innerHTML;
} else {
var Rowz = secondTable.insertRow();
for (var k = 0; k < 4; k += 1) {
Rowz.insertCell(k);
}
Rowz.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Rowz.cells[1].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
}
}
}
}
Row.cells[2].appendChild(Sellbtn);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table border="1">
<thead>
<th>Item</th>
<th>Sold</th>
<th>
<button onclick="insertRow()">Insert</button>
</th>
</thead>
<tbody id="firstTableBody">
</tbody>
</table>
<table border="1">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTable">
</tbody>
</table>
</body>
I insert a row with randomly inserted fruit name and a dynamically added button called sell. When I click on sell it should check if the fruit name of that row exists in the second table or not if so then it should add the sold amount in the row that's in the second table that has the same name. If not then simply add a new row in the second table with the name and sold amount. jQuery is ok.
here is a possible solution, replacement for your function Sell()
Sellbtn.onclick = function Sell() {
var found = false,
rows = secondTable.rows,
numrows = rows.length,
tofind = this.parentNode.parentNode.cells[0].innerHTML,
foundin,
numToAdd = parseInt(this.parentNode.parentNode.cells[1].innerHTML),
num,
x;
for(x=0;x<numrows;x++){
if(rows[x].cells[0].innerHTML === tofind){
found = true;
foundin = x;
}
}
if(found){
num = parseInt(rows[foundin].cells[1].innerHTML) + numToAdd;
rows[foundin].cells[1].innerHTML = num;
}
else{
var Row = secondTable.insertRow();
for (var f = 0; f < 2; f += 1) {
Row.insertCell(f);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
}
}
is this what you're looking for?
$(document).ready(function() {
$('.insert').on('click', function() {
var Fruits = ["Apples", "Oranges", "Strawberries"];
var random_Fruit = Fruits[Math.floor(Math.random() * Fruits.length)];
var clone = $('#template').clone(true).attr('id', '');
clone.css('display', '');
clone.closest('tr').find('.item').html(random_Fruit);
clone.appendTo('#firstTableBody');
});
$('#firstTableBody').on('click', '.sell', function(e) {
e.preventDefault();
var item = $(this).closest('tr').find('.item').html();
var add = parseInt($(this).closest('tr').find('.number').html());
var inTable2 = [];
$('#secondTable tr').each(function() {
var fruit = $(this).find('.item').html();
inTable2.push(fruit);
});
console.log(inTable2);
if ($.inArray(item, inTable2) > -1) {
console.log('in array');
$('#secondTable tr').each(function() {
var fruitIn2 = $(this).find('.item').html();
if (fruitIn2 == item) {
var sold = parseInt($(this).find('.number').html());
$(this).find('.number').html(sold + add);
}
});
}
else {
console.log('add');
var clone = $('#template').clone(true).attr('id', '');
clone.css('display', '');
clone.closest('tr').find('.item').html(item);
clone.closest('tr').find('.sellTd').remove();
clone.appendTo('#secondTable');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1">
<thead>
<th>Item</th>
<th>Number</th>
<th>
<button class="insert">Insert</button>
</th>
</thead>
<tbody id="firstTableBody">
<tr id="template" class="fruit" style="display:none;">
<td class="item"></td>
<td class="number">100</td>
<td class="sellTd"><button class="sell">Sell</button></td>
</tr>
</tbody>
</table>
<br/><br/>
<table border="1">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTable">
</tbody>
</table>
sorry i kinda used all jquery cause it makes it simpler for me to code in and think xp but it works :D

Categories