I'm pretty new in Javascript/Jquery, currently still learning and so here I am seeking help. I would like to insert different images randomly (the location changes everytime i refresh the page) into table cells using Javascript/Jquery and not touching HTML/CSS.
I have tried using append to insert the images, however every image appears in all table cells which weren't what I wanted. I have also tried backgroundrepeat: no repeat but it doesn't work. It would be good if there's some simple coding that would work, so it will be easier for me to understand.
I can't use getElementById cause my separated js file can't detect the ID from the HTML file
HTML:
<table id="Image">
<tr>
<td><div class="ImageHere" value=1></div></td>
<td><div class="ImageHere" value=2></div></td>
<td><div class="ImageHere" value=3></div></td>
<td><div class="ImageHere" value=4></div></td>
<td><div class="ImageHere" value=5></div></td>
</tr>
<tr>
<td><div class="ImageHere" value=6></div></td>
<td><div class="ImageHere" value=7></div></td>
<td><div class="ImageHere" value=8></div></td>
<td><div class="ImageHere" value=9></div></td>
<td><div class="ImageHere" value=10></div></td>
</tr>
</table>
my jQuery best try:
$(document).ready(function(){
$(".ImageHere").append("<img src='images/card.jpg' width='100%' height='100%' />" ) });
});
I hope that can help!
const divs = [...document.querySelectorAll('.ImageHere')];
const images =
[
'https://i.pinimg.com/originals/d4/7e/9e/d47e9e4a28894bfbd416b4f53ca15b95.jpg',
'https://fedoraproject.org/w/uploads/thumb/1/16/Sunset-in-pennsylvania-960px.jpg/285px-Sunset-in-pennsylvania-960px.jpg',
'https://fedoraproject.org/w/uploads/thumb/a/a0/F26-final-night-default-wallpaper-standard.png/300px-F26-final-night-default-wallpaper-standard.png',
'https://eldenring.wiki.fextralife.com/file/Elden-Ring/elden-ring-wiki-screenshot-art-trailer5.jpg?v=1560119240021',
'https://pbs.twimg.com/media/D9oueVsX4AAW3Wk.jpg',
'https://pub-static.haozhaopian.net/static/web/appv2/images/landscape29bb2ef5b72f60c71199d5c22c979eadc.jpg',
'https://images.unsplash.com/photo-1462899006636-339e08d1844e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80',
'https://picjumbo.com/wp-content/uploads/free-stock-images-1080x720.jpg',
'https://destinations.com.ua/storage/crop/articles/avatar_291_max.jpg',
'https://get.wallhere.com/photo/sunlight-women-outdoors-women-model-portrait-blonde-long-hair-nature-photography-dress-Xenia-Kokoreva-river-fashion-hair-white-clothing-spring-Person-skin-clothing-supermodel-girl-beauty-season-woman-lady-photograph-blond-portrait-photography-photo-shoot-brown-hair-art-model-320309.jpg'
];
const suffelImages = shuffle(images);
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
divs.forEach((div, i) => {
div.innerHTML = `<img src="${suffelImages[i]}" />`;
});
// CSS
img {
width: 300px;
height: 300px;
}
Your HTML is invalid. HTMLDivElement does not have a valueattribute. Use data-value instead.
Here's an example. For the sake of simplicity, this inserts <hr /> instead of images. Adjust at your own pleasure.
const imageDivs = document.querySelectorAll('#Image .ImageHere');
document.getElementById('foo').addEventListener('click', insertRandomHr)
function insertRandomHr() {
imageDivs[Math.floor(Math.random()*imageDivs.length)].innerHTML += '<hr />';
}
#Image { width: 100%; }
.ImageHere::before { content: attr(data-value); }
<table id="Image">
<tr>
<td>
<div class="ImageHere" data-value=1></div>
</td>
<td>
<div class="ImageHere" data-value=2></div>
</td>
<td>
<div class="ImageHere" data-value=3></div>
</td>
<td>
<div class="ImageHere" data-value=4></div>
</td>
<td>
<div class="ImageHere" data-value=5></div>
</td>
</tr>
<tr>
<td>
<div class="ImageHere" data-value=6></div>
</td>
<td>
<div class="ImageHere" data-value=7></div>
</td>
<td>
<div class="ImageHere" data-value=8></div>
</td>
<td>
<div class="ImageHere" data-value=9></div>
</td>
<td>
<div class="ImageHere" data-value=10></div>
</td>
</tr>
</table>
<button id="foo" type="button">Insert <hr /> into random div</button>
Hint: If the sole reason to have those invalid value attributes in the first place was to use that for randomly assigning the image to a div, you don't need that.
You can first define array of your images which need to be inserted , then make this array arrange values randomly , then using .forEach JS function Or .each JQuery Function to loop and insert these images into your table randomly
let's start with this code and read my comments on it to understand what i mean better
var images= ['image1.jpg','test.png','logo.png'] // array of your images
var randomArr = [] // new empty array which will have random values
for(var i= 0 ; i < images.length;i++){
var item = images[Math.floor(Math.random() * images.length)]
// this condition to prevent doublicate elements
if(!randomArr.includes(item)){
randomArr.push(item)
}else{
i = i - 1;
}
}
// now we have new array with random images
// lets start to insert these images into table
$("table#Image .ImageHere").each(function(index, value){
if(index > randomArr.length) {
// check if elements more than array of images and set default image
$(this).html("<img src='default.jpg' />")
}else{
$(this).html("<img src='"+randomArr[index]+"' />")
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table id="Image">
<tr>
<td><div class="ImageHere" value=1>ddd</div></td>
<td><div class="ImageHere" value=2></div></td>
<td><div class="ImageHere" value=3></div></td>
<td><div class="ImageHere" value=4></div></td>
<td><div class="ImageHere" value=5></div></td>
</tr>
<tr>
<td><div class="ImageHere" value=6></div></td>
<td><div class="ImageHere" value=7></div></td>
<td><div class="ImageHere" value=8></div></td>
<td><div class="ImageHere" value=9></div></td>
<td><div class="ImageHere" value=10></div></td>
</tr>
</table>
One solution could be to generate a random index from all the image containers that you have created in your table cells. You could then insert a programmatically created image element in the image container located at the generated index.
Example:
// Returns a random index, from 0..max
const randomIndex = (max) => Math.floor(Math.random() * Math.floor(max));
// Returns an image element with a random image
const createImage = () => {
const el = document.createElement('img');
el.src = 'https://picsum.photos/100';
return el;
};
// List of all image containers
const containers = document.querySelectorAll('.ImageHere');
// Generate random index and add an image to the container at that index
const index = randomIndex(containers.length);
containers[index].appendChild(createImage());
table {
border-collapse: collapse;
}
td {
width: 100px;
height: 100px;
border: 1px solid black;
padding: 0;
}
img {
display: block;
}
<table id="Image">
<tbody>
<tr>
<td>
<div class="ImageHere"></div>
</td>
<td>
<div class="ImageHere"></div>
</td>
<td>
<div class="ImageHere"></div>
</td>
<td>
<div class="ImageHere"></div>
</td>
<td>
<div class="ImageHere"></div>
</td>
</tr>
<tr>
<td>
<div class="ImageHere"></div>
</td>
<td>
<div class="ImageHere"></div>
</td>
<td>
<div class="ImageHere"></div>
</td>
<td>
<div class="ImageHere"></div>
</td>
<td>
<div class="ImageHere"></div>
</td>
</tr>
</tbody>
</table>
document.querySelectorAll('.ImageHere').item(n)
or
$('.ImageHere').eq(n)
where n is the index of a random number.
Related
I have the following html table:
<table border="1" cellpadding="5" class="test">
<tr>
<td class="talent-cell"><div class="btn7" data-value="0">aaa</div></td>
<td class="talent-cell"><div class="btn8" data-value="1">bbb</div></td>
<td class="talent-cell"><div class="btn9" data-value="2">ccc</div></td>
</tr>
<tr>
<td class="talent-cell"><div class="btn7" data-value="0">ddd</div></td>
<td class="talent-cell"><div class="btn8" data-value="1">eee</div></td>
<td class="talent-cell"><div class="btn9" data-value="2">fff</div></td>
</tr>
<tr>
<td class="talent-cell"><div class="btn7" data-value="0">ggg</div></td>
<td class="talent-cell"><div class="btn8" data-value="1">hhh</div></td>
<td class="talent-cell"><div class="btn9" data-value="2">iii</div></td>
</tr>
</table>
If you click on a "div attribute" inside a table cell I need to get the "data-value" of the clicked div attribute. After that I build a query string to use it with "URLSearchParams". This works so far.
Now I need a certain condition. It should be only allowed to select one div-attribute per table row and column. But I don't know how to implement this condition in my code.
This is the Fiddle and the code:
var btn7;
var btn8;
var btn9;
$('.btn7').click(function () {
if ($(this).attr('data-selected') === 'true') {
$(this).attr('data-selected', 'false');
$(this).removeClass('selected');
} else {
$(this).closest('tr').find('.btn7').not(this)
.removeClass('selected').attr('data-selected', 'false');
$(this).attr('data-selected', 'true');
$(this).addClass('selected');
params.set('var7', $(this).data("value"));
window.history.replaceState({}, '', `?${params}`);
}
});
$('.btn8').click(function () {
if ($(this).attr('data-selected') === 'true') {
$(this).attr('data-selected', 'false');
$(this).removeClass('selected');
} else {
$(this).closest('tr').find('.btn8').not(this)
.removeClass('selected').attr('data-selected', 'false');
$(this).attr('data-selected', 'true');
$(this).addClass('selected');
params.set('var8', $(this).data("value"));
window.history.replaceState({}, '', `?${params}`);
}
});
$('.btn9').click(function () {
if ($(this).attr('data-selected') === 'true') {
$(this).attr('data-selected', 'false');
$(this).removeClass('selected');
} else {
$(this).closest('tr').find('.btn9').not(this)
.removeClass('selected').attr('data-selected', 'false');
$(this).attr('data-selected', 'true');
$(this).addClass('selected');
params.set('var9', $(this).data("value"));
window.history.replaceState({}, '', `?${params}`);
}
});
const params = new URLSearchParams({
var7: btn7,
var8: btn8,
var9: btn9,
});
Idea
Mark each table cell with a data- attribute indicating its respective row and column, and maintain 2 arrays that hold the currently selected element (if any) for each of the columns and row.
Implementation
The following code implements the selection logic. Based on the arrays holding the currently active selections you can visit all relevant elements and assemble the parameters when you send a request to the server.
The specs of single cell/row selection implies that there will usually be rows and columns that do not carry a selection.
Note that the case of expressly deselecting a cell is not handled.
The code does not resort to jquery.
<!DOCTYPE html>
<html>
<head>
<title>SO _: 1-in-a-row, 1-in-a-col selection</title>
<style type="text/css">
.selected {
background: #333;
color: #fff;
}
</style>
<script type="text/javascript">
let a_colSelection = new Array(3)
, a_rowSelection = new Array(3)
;
document.addEventListener ( 'DOMContentLoaded', () => {
Array.from(document.querySelectorAll('div[data-row][data-col]')).forEach ( el => {
el.addEventListener ( 'click', eve => {
let c = parseInt(eve.target.getAttribute('data-col'))
, r = parseInt(eve.target.getAttribute('data-row'))
;
if (a_colSelection[c] !== undefined) {
document.querySelector(`div[data-col="${a_colSelection[c][1]}"][data-row="${a_colSelection[c][0]}"]`).classList.remove("selected");
}
if (a_rowSelection[r] !== undefined) {
document.querySelector(`div[data-col="${a_rowSelection[r][1]}"][data-row="${a_rowSelection[r][0]}"]`).classList.remove("selected");
}
a_colSelection[c] = [r, c];
a_rowSelection[r] = [r, c];
document.querySelector(`div[data-col="${a_colSelection[c][1]}"][data-row="${a_rowSelection[r][0]}"]`).classList.add("selected");
});
});
});
</script>
</head>
<body>
<table border="1" cellpadding="5" class="test">
<tr>
<td class="talent-cell"><div data-value="0" data-col="0" data-row="0">aaa</div></td>
<td class="talent-cell"><div data-value="1" data-col="1" data-row="0">bbb</div></td>
<td class="talent-cell"><div data-value="2" data-col="2" data-row="0">ccc</div></td>
</tr>
<tr>
<td class="talent-cell"><div data-value="0" data-col="0" data-row="1">ddd</div></td>
<td class="talent-cell"><div data-value="1" data-col="1" data-row="1">eee</div></td>
<td class="talent-cell"><div data-value="2" data-col="2" data-row="1">fff</div></td>
</tr>
<tr>
<td class="talent-cell"><div data-value="0" data-col="0" data-row="2">ggg</div></td>
<td class="talent-cell"><div data-value="1" data-col="1" data-row="2">hhh</div></td>
<td class="talent-cell"><div data-value="2" data-col="2" data-row="2">iii</div></td>
</tr>
</table>
</body>
</html>
Consider the following.
Fiddle: https://jsfiddle.net/Twisty/dzng31f5/39/
HTML
<table border="1" cellpadding="5" class="test">
<tr class="var7">
<td class="talent-cell">
<div class="btn" data-value="0">aaa</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="1">bbb</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="2">ccc</div>
</td>
</tr>
<tr class="var8">
<td class="talent-cell">
<div class="btn" data-value="0">ddd</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="1">eee</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="2">fff</div>
</td>
</tr>
<tr class="var9">
<td class="talent-cell">
<div class="btn" data-value="0">ggg</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="1">hhh</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="2">iii</div>
</td>
</tr>
</table>
I adjusted the HTML Structure, such that each Row has a Class that represents the Index name that will be used in the Object.
jQuery
$(function() {
function checkCol(colIndex, table) {
var result = true;
console.log("Col Index:" + colIndex)
$("tbody tr", table).each(function(i, el) {
result = result && !$("td:eq(" + colIndex + ") div.btn", el).hasClass("selected");
});
return !result;
}
function checkRow(target, row) {
var isInCol = checkCol($(target).parent().index(), $(row).closest("table"));
if (!isInCol) {
if ($(".selected", row).length) {
$(".selected", row).removeClass("selected");
$(target).addClass("selected");
} else {
$(target).addClass("selected");
}
}
}
var selected = {};
$('.btn').click(function(event) {
var row = $(this).closest("tr");
checkRow(this, row);
$(".test tbody tr").each(function(i, el) {
selected[$(el).attr("class")] = $(".selected", el).length ? $(".selected", el).data("value") : "";
});
console.log(selected);
var params = new URLSearchParams(selected);
console.log(params.toString());
});
});
You can now use selected as your Data in a POST or GET call.
Updated
I had missed that each Row and Column needed to be unique. Code is updated to use Functions to check both conditions.
"Now I need a certain condition. It should be only allowed to select one div-attribute per table row and column."
The versatility of jQuery is leveraged by the use of this because it narrows down from many objects (all <td> in <table>) to a single object (<td> the user clicked). The behavior needed is common with radio button groups called "mutual exclusive selection", using .not(this) makes it simple.
In HTML,
assign a common class to each <div> (ex. '.col', see Figure I)
assign a class to each <div> that corresponds to the value of it's [data-value] (ex. '.c0', see Figure I)
Figure I
<div class='col c0' data-value='0'>
I did not include the params part in OP since it's beyond the scope of the question (see beginning of this answer). The values are stored in object C and is easily accessible (ex. C.c0).
BTW, I hope that the logic is different with your real code. For example, there is no difference between .c0 2nd row and .c0 1st row.
Details are commented in example below
// Declare object to store [data-value]
let C = {};
// Any click on a .col calls the event handler
$('.col').on('click', function() {
// Flip .selected on this .col
$(this).toggleClass('selected');
// If this .col is flipped to be .selected...
if ($(this).is('.selected')) {
//... get this .col [data-value] (0, 1, or 2)...
let idx = $(this).data('value');
/*
... find all .c0, .c1, or .c2 BUT NOT this .col and
remove .selected from them...
*/
$('.c' + idx).not(this).removeClass('selected');
/*
... then find the closest <tr>, then find all .col of
<tr> BUT NOT this .col and remove .selected from them
*/
$(this).closest('tr').find('.col')
.not(this).removeClass('selected');
// set key 'c0', 'c1', or 'c2' of C to this .col [data-value]
C['c'+idx] = $(this).data('value');
}
console.log(C);
});
<table border="1" cellpadding="5" class="test">
<tr>
<td><div class="col c0" data-value="0">aaa</div></td>
<td><div class="col c1" data-value="1">bbb</div></td>
<td><div class="col c2" data-value="2">ccc</div></td>
</tr>
<tr>
<td><div class="col c0" data-value="0">aaa</div></td>
<td><div class="col c1" data-value="1">bbb</div></td>
<td><div class="col c2" data-value="2">ccc</div></td>
</tr>
<tr>
<td><div class="col c0" data-value="0">aaa</div></td>
<td><div class="col c1" data-value="1">bbb</div></td>
<td><div class="col c2" data-value="2">ccc</div></td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
var tada =document.querySelectorAll("#element > table tr:nth-child(n+0) td:nth-child(1)")[0].outerText
this gains first
var tada =document.querySelectorAll("#element > table tr:nth-child(n+0) td:nth-child(1)")[1].outerText
This kind of text how can it be changed to fit all the values?
How do I change [0].outerText
0 to all numbers?
or how to get only the first number from the picture (console.log)
They just need to get those first numbers the code of the page looks like this
http://jsfiddle.net/8cuagzjd/1/
and yet how to calculate all array?
This is my approach,
There is a NaN element that I didn´t know if you want to remove or remain there.
The code split the td tag and get the last part (after the div). Then just parseInt() the value and you will get the number.
As a result you will get an array with the numbers.
//just commented this for tests purpose
//var tada = Array.from(document.querySelectorAll("#element > table tr:nth-child(n+0) td:nth-child(1)"));
var tada = Array.from(document.querySelectorAll("table tr:nth-child(n+0) td:nth-child(1)"));
let numbers = [];
tada.forEach(e => {
let num = parseInt(e.innerHTML.split("</div>")[1]);
//to avoid adding Nan
if (!isNaN(num)) numbers.push(num);
});
let sum = numbers.reduce((a, b) => a + b, 0);
console.log(sum);
<div class="trainqueue_wrap" id="trainqueue_wrap_barracks">
<table class="vis" style="width: 100%">
<tbody>
<tr>
<th style="width: 25%">Výcvik</th>
<th>Trvání</th>
<th>Zhotovení</th>
<th style="width: 150px">Ukončení *</th>
<th style="background:none !important; width: 2%"></th>
</tr>
<tr class="lit">
<td class="lit-item">
<div class="unit_sprite unit_sprite_smaller sword"></div>
19 Šermířů
</td>
<td class="lit-item"><span class="">0:00:37</span></td>
<td class="lit-item">dnes v 00:42:11 hodin</td>
<td class="lit-item"><a class="btn btn-cancel" onclick="return TrainOverview.cancelOrder(1645)" href="/">Storno</a></td>
<td class="lit-item" style="background:none !important;"></td>
</tr>
</tbody>
<tbody id="trainqueue_barracks">
<tr class="sortable_row" id="trainorder_0">
<td class="">
<div class="unit_sprite unit_sprite_smaller spear"></div>
20 Kopiníků
</td>
<td>0:00:32</td>
<td>dnes v 00:42:43 hodin</td>
<td><a class="btn btn-cancel" onclick="return TrainOverview.cancelOrder(1646)" href="/">Storno</a></td>
</tr>
<tr class="sortable_row" id="trainorder_1">
<td class="">
<div class="unit_sprite unit_sprite_smaller spear"></div>
20 Kopiníků
</td>
<td>0:00:32</td>
<td>dnes v 00:43:15 hodin</td>
<td><a class="btn btn-cancel" onclick="return TrainOverview.cancelOrder(1647)" href="/">Storno</a></td>
</tr>
<tr>
<td colspan="3"> </td>
<td class="lit-item">
<a class="evt-confirm btn btn-cancel nowrap" data-confirm-msg="Opravdu chceš zrušit veškerou rekrutaci?" href="">Zrušit vše</a></td>
<th style="background:none !important;"></th>
</tr>
</tbody>
</table>
</div>
Great day Community,i'm facing clone whole table problem, if it have solution of clone several row it will be helping a lots.
If using document.getElementsByTagName("table")[2]; it can clone the table and put it in body because i'm using document.body.appendChild(myClone) to do it.
Here is some code:
Solution 1:
function myFunction() {
myTable = document.getElementsByTagName("table")[2]; // doesn't use any table id
myClone = myTable.cloneNode(true);
var y = document.body.appendChild(myClone);
}
Solution 2:
function myFunction() {
var x = document.getElementById("0"); // using this to find auto genereate id for table
test = x.cloneNode(true);
}
Html Display:
<table>
<tr>
<td>
<table id="0">
<tr>
<td><span></span>Name:<input type="text" value="Tom"/> </td>
<td><span> </span>Age:<input type="text" value="25"/> </td>
<td><span> </span>Email:<input type="text" value="tom#gmail.com"/> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table id="1">
<tr>
<td><span></span>Name:<input type="text" value="Alice"/> </td>
<td><span> </span>Age:<input type="text" value="22"/> </td>
<td><span> </span>Email:<input type="text" value="alice#gmail.com"/> </td>
</tr>
</table>
<input type="button" onclick="myFunction()"/>
</td>
</tr>
</table>
Expected result clone the table after the button, the table inside will not have more than 5.
Please help thank you.
Although Dominic Amal Joe F's answer was on the right track, it had some flaws, as well as the structure of the OP table. I think this code would work properly:
function myFunction(){
// get main table body
var tableBody = document.getElementById('mytable').children[0];
// get existing rows
var rows = tableBody.children.length;
// clone the last row (which contains the last table)
var newRow = tableBody.children[rows-1].cloneNode(true);
// get the new row table
var newTable = newRow.children[0].children[0]
// change the table id
newTable.setAttribute('id', rows);
// reset the inputs values
var cells = newTable.children[0].children[0].children;
for (var i=0; i<cells.length; i++) {
cells[i].children[1].value = "";
}
// append the new row to the main table body
tableBody.appendChild(newRow);
}
<table id="mytable">
<tr>
<td>
<table id="0">
<tr>
<td><span>Name:</span><input type="text" value="Tom"/></td>
<td><span>Age:</span><input type="number" value="25"/></td>
<td><span>Email:</span><input type="email" value="tom#gmail.com"/></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table id="1">
<tr>
<td><span>Name:</span><input type="text" value="Alice"/></td>
<td><span>Age:</span><input type="number" value="22"/></td>
<td><span>Email:</span><input type="email" value="alice#gmail.com"/></td>
</tr>
</table>
</td>
</tr>
</table>
<button onclick="myFunction()">Clone</button>
I feel the following code will help you.
HTML
<table>
<button onclick="myFunction()">clone</button>
<tr>
<table id="parent-table">
<tr id="parent-row">
<td><span></span>Name:<input type="text" value="Tom"/> </td>
<td><span> </span>Age:<input type="text" value="25"/> </td>
<td><span> </span>Email:<input type="text" value="tom#gmail.com"/></td>
</tr>
</table>
</tr>
</table>
JavaScript
function myFunction(){
let parentTable = document.getElementById("parent-table");
let parentRow = document.getElementsByTagName('tr')
let clone = parentRow[1].cloneNode(true);
parentTable.appendChild(clone)
}
I am trying to change the color of the selected row from a table on a onmousedown event and reset all others (or keep them the same) . Only one row can be red at a time while all others are green.
What I have tried:
function HighLight(id) {
var rows = $('#tbl > tbody > tr').each(function(elem) {
elem.style.background = 'green';
})
var tr = document.getElementById(id);
tr.style.background = 'red';
}
<table id="tbl">
<tr id="tr1" style="background-color:aquamarine" onmousedown="Highlight(e)">
<td>
v1
</td>
</tr>
<tr id="tr2" style="background-color:aquamarine" onmousedown="Highlight(e)">
<td>
v2
</td>
</tr>
<tr id="tr3" style="background-color:aquamarine" onmousedown="Highlight(e)">
<td>
v3
</td>
</tr>
</table>
Ideally I would like to store the old selected row so that I won't reset all others at each new selection, but in case I can't reset all would do it.
P.S I need to make due with the id that i am provided.I am using interop so the id is coming from the exterior. All my tr have that method injected in them.
The function name is wrong its Highlight not HighLight
To pass the id of the element on function call you cannot just pass any variable(e in your case). Use this.getAttribute('id') to get the id.
In the each() the argument elem represented the index of the element and not the element itself. Introduce another argument for index.
function Highlight(id) {
var rows = $('#tbl > tbody > tr').each(function(i,elem) {
elem.style.background = 'green';
})
var tr = document.getElementById(id);
tr.style.background = 'red';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1" style="background-color:aquamarine" onmousedown="Highlight(this.getAttribute('id'))">
<td>
v1
</td>
</tr>
<tr id="tr2" style="background-color:aquamarine" onmousedown="Highlight(this.getAttribute('id'))">
<td>
v2
</td>
</tr>
<tr id="tr3" style="background-color:aquamarine" onmousedown="Highlight(this.getAttribute('id'))">
<td>
v3
</td>
</tr>
</table>
Here is a quick example on how can you do that.
$("table tr").on('click', function(){
$(".highlighted").removeClass("highlighted");
$(this).addClass("highlighted");
});
table tr {
background: green;
}
table tr.highlighted {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1">
<td>
v1
</td>
</tr>
<tr id="tr2">
<td>
v2
</td>
</tr>
<tr id="tr3">
<td>
v3
</td>
</tr>
</table>
Here is how it works:
It binds a click event to every row in the table (tr),
Every time you click on a row, all elements that has a class called highlighted loose it and the row that you clicked gets the class highlighted,
In css you can change the default background color for all rows and the color after highlighting.
If you don't want to use a css, here is similar function but instead of adding and removing class it does the same with the inline css property.
$("table tr").on('click', function(){
$("table tr").css("background", "green");
$(this).css("background", "red");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1" style="background: green;">
<td>
v1
</td>
</tr>
<tr id="tr2" style="background: green;">
<td>
v2
</td>
</tr>
<tr id="tr3" style="background: green;">
<td>
v3
</td>
</tr>
</table>
But I do not recommend the second solution.
You can have two css classes; one for selected row and other for remaining rows.
On click of the row, you can add the "selected" class to that row.
$("#tbl tr").click(function(){
var $this = $(this);
//remove the previous row selection, if any
$("#tbl tr.selected").removeClass("selected");
//add selected class to the current row
$this.addClass("selected");
});
#tbl tr{
background-color: aquamarine;
}
#tbl tr.selected{
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1">
<td>
v1
</td>
</tr>
<tr id="tr2" >
<td>
v2
</td>
</tr>
<tr id="tr3" >
<td>
v3
</td>
</tr>
</table>
You can do like this.by using class you can carry out other operations
$("#tbl").on("click", "tr", function() {
$(' tr').removeClass("Red")
$(this).addClass("Red")
});
.Red {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1">
<td>
v1
</td>
</tr>
<tr id="tr2">
<td>
v2
</td>
</tr>
<tr id="tr3">
<td>
v3
</td>
</tr>
</table>
Several issues:
JS is case sensitive, so Highlight and HighLight (capital L) is not the same. I renamed the HighLight function to Highlight (lowercase l)
Use parameter this on function call in event handler attribute. This hands over the HTML element of the event handler attribute over to the event handler function (Highlight in your case)
Callback function of jQuery's each method has the index as a first parameter and the element as second
This makes your code work
function Highlight(tr) {
var rows = $('#tbl > tbody > tr').each(function(index, elem) {
elem.style.backgroundColor = 'green';
})
tr.style.background = 'red';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1" style="background-color:aquamarine" onmousedown="Highlight(this)">
<td>
v1
</td>
<td>
v1
</td>
<td>
v1
</td>
</tr>
<tr id="tr2" style="background-color:aquamarine" onmousedown="Highlight(this)">
<td>
v2
</td>
<td>
v2
</td>
<td>
v2
</td>
</tr>
<tr id="tr3" style="background-color:aquamarine" onmousedown="Highlight(this)">
<td>
v3
</td>
<td>
v3
</td>
<td>
v3
</td>
</tr>
</table>
There are some more things you can do to enhance your code
Don't use style in your JS code, but set classes for CSS
Don't use HTML onmousedown attributes, but JS addEventListeners
Replace jQuery code with VanillaJS
console.clear()
const rows = document.querySelectorAll('#tbl > tbody > tr');
for (row of rows) {
row.addEventListener('mousedown', Highlight)
}
function Highlight(e) {
e.preventDefault()
const tr = this
const rows = document.querySelectorAll('#tbl > tbody > tr');
for (row of rows) {
row.classList.remove('highlight')
row.classList.add('highlight-siblings')
}
tr.classList.remove('highlight-siblings')
tr.classList.add('highlight')
}
/* 1. */
tr {
background-color: aquamarine;
}
tr.highlight-siblings{
background-color: green;
}
tr.highlight{
background-color: red;
}
<table id="tbl">
<tr>
<td>
v1
</td>
<td>
v1
</td>
<td>
v1
</td>
</tr>
<tr>
<td>
v2
</td>
<td>
v2
</td>
<td>
v2
</td>
</tr>
<tr>
<td>
v3
</td>
<td>
v3
</td>
<td>
v3
</td>
</tr>
</table>
I have the following HTML Table,
<table id="items">
<tr class="total_up">
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Total</td>
<td class="total-value" id="total"><div id="totalone">$875.00</div></td>
</tr>
<tr class="disc" id="disc">
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Discount</td>
<td class="total-value" id="discount"><div id="discountid"><input type="text" name="disco" class="dis"/></div> </td>
</tr>
<tr class="tax_up">
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line balance">tax</td>
<td class="total-value" id="tax"><div id="tax">00</div></td>
</tr>
</table>
When i click on the button with id Discount, I need to change the value to the TD inside the div Tag with id "total" and set its value to another JavaScript variable?I tried the following, but it's not working.
$(".discountbtn").click(function(){
var test=$("#items #disc .dis").val(); //Easiest method
console.log("lol");
console.log(test);
var tot = roundNumber(test,2);
var new_tot=window.finale-tot;
console.log(window.finale);
console.log(new_tot);
$('#items #totalone').html("$"+new_tot);
//alert("button");
});
Try with my code that help you
change HTML <div id="totalone">$875.00</div> to $<span id="totalone">875.00</span>
$(document).ready(function() {
$("#discountbtn").click(function(){
var test=$("#items #disc .dis").val();
console.log(test);
var oldTotal = $("#totalone").text();
console.log(oldTotal);
var tot = Math.round(test * 100) / 100;
var new_tot=parseFloat(oldTotal)-tot;
console.log(new_tot);
$('#items #total').html(new_tot); //It was a jQuery selector glitch.
});
});
$('#items #totalone').html("$"+new_tot);