This question already has answers here:
How to modify a CSS display property from JavaScript?
(3 answers)
Closed 8 years ago.
I have two tables showing different data and on the top of the page there are two buttons. When you click on one button I want it to show the data for Table A, and when you click on the other button I want it to hide Table A, and show the data in Table B. The default views for both tables are set to Hide upon page loading and only show when each button is clicked. What is the javascript functions to make this happen?
Plain JS.
<table border="1" id="tableA">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<table border="1" id="tableB">
<tr>
<td>cell 5</td>
<td>cell 6</td>
</tr>
<tr>
<td>cell 7</td>
<td>cell 8</td>
</tr>
</table>
<input type="button" id="showTableA" value="Table A">
<input type="button" id="showTableB" value="Table B">
var tableA = document.getElementById("tableA");
var tableB = document.getElementById("tableB");
var btnTabA = document.getElementById("showTableA");
var btnTabB = document.getElementById("showTableB");
btnTabA.onclick = function () {
tableA.style.display = "table";
tableB.style.display = "none";
}
btnTabB.onclick = function () {
tableA.style.display = "none";
tableB.style.display = "table";
}
FIDDLE
Assuming jQuery:
(function($) {
$(function() {
var tableA = $('#tableA'),
tableB = $('#tableB'),
buttonA = $('#buttonA'),
buttonB = $('#buttonB');
buttonA.click(function() {
tableA.show();
tableB.hide();
});
buttonB.click(function() {
tableA.hide();
tableB.show();
});
});
})(jQuery);
No offense, but even an extremely cursory search of Google or Stack Overflow would turn up countless examples of how to do this. Chances are your question will be closed, as part of the S.O. code of conduct states that you have to show at least a minimal amount of effort to get things working.
Related
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
So I have a piece of code to create a table with some data in it. The first column contains checkboxes, other columns are just regular data.
What I want is that when I click anywhere on a random row (except for header), that entire row's background is turning into yellow (initially white) and the checkbox in that row is ticked. If I click again, everything in the row back to its normal (white row and unticked checkbox).
When I click right at the checkbox, everything acts as expected. However, when I click elsewhere, only the background is changed. I have checked the checked attribute of the checkbox and it is changed whenever I click (which is like normal). I don't know why this happens. I have looked through many posts with similar issues but it is not helped. I am only a beginner at Javascript and HTML. Please help me with this. Thank you very much!
function changeColorRow(number) {
var elem = document.getElementsByTagName("tr")[number]
var curr_check = document.getElementsByClassName("checkbox").checked
if (!curr_check) {
elem.style.backgroundColor = "yellow"
document.getElementsByClassName("checkbox").checked = true
} else {
elem.style.backgroundColor = "white"
document.getElementsByClassName("checkbox").checked = false
}
}
<h1>List of companies</h1>
<table id="company">
<tr>
<th>Choose</th>
<th>ID</th>
<th>Company</th>
<th>Website</th>
</tr>
<tr onclick="changeColorRow(1)">
<td><input type="checkbox" class="checkbox"></td>
<td>1</td>
<td>ECOPRO Co., Ltd</td>
<td>http://www.ecoprovn.com</td>
</tr>
<tr onclick="changeColorRow(2)">
<td><input type="checkbox" class="checkbox"></td>
<td>2</td>
<td>WAVINA.COM</td>
<td>http://www.wavina.com</td>
</tr>
</table>
document.getElementsByClassName returns an array like structure, You have to use index to get that particular element at that index.
document.getElementsByClassName("checkbox")
You can get the index of the clicked row as
index = number - 1
const allCheckbox = document.getElementsByClassName("checkbox");
function changeColorRow(number) {
const index = number - 1;
var elem = document.getElementsByTagName("tr")[number]
var curr_check = document.getElementsByClassName("checkbox")[index].checked
if (!curr_check) elem.style.backgroundColor = "yellow"
else elem.style.backgroundColor = "white"
allCheckbox[index].checked = !allCheckbox[index].checked
}
[...allCheckbox].forEach(cb => {
cb.addEventListener("change", (e) => changeColorRow(parseInt(e.target.dataset.index)))
})
tr {
cursor: default;
user-select: none;
}
<h1>List of companies</h1>
<table id="company">
<tr>
<th>Choose</th>
<th>ID</th>
<th>Company</th>
<th>Website</th>
</tr>
<tr onclick="changeColorRow(1)">
<td><input type="checkbox" class="checkbox" data-index="1"></td>
<td>1</td>
<td>ECOPRO Co., Ltd</td>
<td>http://www.ecoprovn.com</td>
</tr>
<tr onclick="changeColorRow(2)">
<td><input type="checkbox" class="checkbox" data-index="2"></td>
<td>2</td>
<td>WAVINA.COM</td>
<td>http://www.wavina.com</td>
</tr>
</table>
I have many tables each one with an ID, (table1,2,3,...), and in each one I have many TD's <td><a href
example :
<table id="myTable1" class="someclass">
<tbody>
<tr>
<td>blablabla</td>
<td>random text</td>
<td>randomtext</td>
</tr>
</tbody>
</table>
</td>
<table id="myTable2" class="someclasse">
<tbody>
<tr>
<td>blablabla</td>
<td>random text</td>
<td>randomtext</td>
</tr>
</tbody>
</table>
</td>
(don't look at the HTML code it's not important for now )
My goal is to open all hrefs within the table "table X" then open them in new tab. I do that with
var els = document.getElementById("myTable1").querySelectorAll("a[href^='https://domaine.']");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
alert(el)
window.open (el,"_blank");
}
It works like a charm. Now I want to add a checkbox to each table, and if checked to open the href on "the" table I checked (I did some innerHTML to "insert" checkbox). Now my question, how can I get the table ID when I'll check the checkbox?
For example I check the table that have "table6" and then every link in that table gets opened.
table id=1 (checkbox)
table id=2 (checkbox)
etc
if i check the checkbox it will get the table with id 2
You can use closest to get the closest table, then you can get the id from that.
// List of checkboxes
let inputs = Array.from(document.querySelectorAll('input[type=checkbox]'))
// Add a click event to each
inputs.forEach(input => {
input.addEventListener('click', e => {
let target = e.currentTarget
// If the checkbox isn't checked end the event
if (!target.checked) return
// Get the table and id
let table = target.closest('table')
let id = table.id
console.log(id)
})
})
<table id="abc">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
<table id="def">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
<table id="ghi">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
<table id="jkl">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
You say that you are adding the checkbox dynamically, so you won't want to do a querySelectorAll like I did above. You will want to add it when it is created like this:
// List of tables
let tables = Array.from(document.querySelectorAll('table'))
// insert the checkbox dynamically
tables.forEach(table => {
table.innerHTML = '<tr><td><input type="checkbox"></td></tr>'
// Get the checkbox
let checkbox = table.querySelector('input[type=checkbox]')
// Add an eventlistener to the checkbox
checkbox.addEventListener('click', click)
})
function click(e) {
let target = e.currentTarget
// If the checkbox isn't checked end the event
if (!target.checked) return
// Get the table and id
let table = target.closest('table')
let id = table.id
console.log(id)
}
<table id="abc">
</table>
<table id="def">
</table>
<table id="ghi">
</table>
<table id="jkl">
</table>
…I want to add a checkbox to each table, and if [it's] checked…open the href [in] "the" table I checked…how can I get the table ID when I'll check the checkbox?
Given that you want to find the id of the <table> within which the check-box <input> is contained in order to select the <table> via its id property you don't need the id; you simply need to find the correct <table>.
To that end I'd suggest placing an event-listener on each of those <table> elements, and opening the relevant links found within. For example (bearing in mind that there are restrictions on opening new windows/tabs on Stack Overflow, I'll simply style the relevant <a> elements rather than opening them):
function highlight(e) {
// here we find the Static NodeList of <a> elements
// contained within the <table> element (the 'this'
// passed from EventTarget.addEventListener()) and
// convert that Array-like collection to an Array
// with Array.from():
Array.from(this.querySelectorAll('a'))
// iterating over the Array of <a> elements using
// Array.prototype.forEach() along with an Arrow
// function:
.forEach(
// here we toggle the 'ifCheckboxChecked' class-name
// via the Element.classList API, adding the class-name
// if the Event.target (the changed check-box, derived
// from the event Object passed to the function from the
// EventTarget.addEventListener function) is checked:
link => link.classList.toggle('ifCheckboxChecked', e.target.checked)
);
}
// converting the Array-like Static NodeList returned
// from document.querySelectorAll() into an Array:
Array.from(document.querySelectorAll('table'))
// iterating over the Array of <table> elements:
.forEach(
// using an Arrow function to pass a reference to the
// current <table> element (from the Array of <table>
// elements to the anonymous function, in which we
// add an event-listener for the 'change' event and
// bind the named highlight() function as the event-
// handler for that event:
table => table.addEventListener('change', highlight)
);
function highlight(e) {
Array.from(this.querySelectorAll('a'))
.forEach(
link => link.classList.toggle('ifCheckboxChecked', e.target.checked)
);
}
Array.from(document.querySelectorAll('table')).forEach(
table => table.addEventListener('change', highlight)
);
body {
counter-reset: tableCount;
}
table {
width: 80%;
margin: 0 auto 1em auto;
border: 1px solid limegreen;
}
table::before {
counter-increment: tableCount;
content: 'table' counter(tableCount);
}
a.ifCheckboxChecked {
background-color: #f90;
}
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
JS Fiddle demo.
References:
CSS:
::before pseudo-element
Using CSS Counters.
JavaScript:
Array.from().
Array.prototype.forEach().
Arrow Functions.
Element.querySelectorAll().
Event.
EventTarget.addEventListener().
I have a html table with a fixed number of rows, of which only the first one is visible from the beginning. Upon clicking a button, row 2 should be revealed. Upon clicking the same button again, row 3 should be revealed, and so on.
Importantly, the full table should be loaded at the beginning (each row contains a specific django formfield), so I do not want to generate additional html rows when clicking the button.
I found lots of stuff on toggling/showing table rows using jQuery, but what I want to do here is I want to show additional rows each time the button is clicked.
My idea was to first initiate and then increment a variable upon clicking in Javascript, and then show an additional row each time. I failed.
I am newbie to Javascript, any suggestions highly appreciated!
$(document).ready(function() {
var counter = 1;
var $rows = $("#fullTable tr");
$("RevealRow").click(function() {
counter++;
$rows.eq(counter).show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="fullTable">
<tr>
<td>Row 1</td>
</tr>
<tr style="display:none;">
<td>Row 2</td>
</tr>
<tr style="display:none;">
<td>Row 3</td>
</tr>
<tr style="display:none;">
<td>Row 4</td>
</tr>
<tr style="display:none;">
<td>Row 5</td>
</tr>
<tr style="display:none;">
<td>Row 6</td>
</tr>
</table>
<button id="RevealRow">Show more rows</button>
Try this jQuery code
$(document).ready(function () {
$("#RevealRow").click(function () {
$("#fullTable tr:visible").next().show();
});
});
I need some help...I have this webpage (http://93.62.201.235/maree/ESPORTAZIONI/MESE/Stazione_PuntaSalute_CanalGrande.html) which creates a table with high tide values in Venice.
I need a specific value (the third cell on the last raw) and get it in a variable...
I tried with this jQuery code only to see if it works with a table I created in an external html page:
function myFunction()
{
$("#result").load("tableappend.html table", function(){
var y = document.getElementById("myTable2").rows[0].cells[0].innerHTML;
console.log(y);
});
}
This is the code of the "external" page:
<html>
<body>
<table id="myTable2" border="1">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<br>
</body>
</html>
It should write "cell 1" on the console.log but it doesn't work...
Any solution?
For any cross domain request you need to consider about CORS(Cross Origin Resource Sharing)
You can achieve this using JSONP for JSON calls
Or send an Origin header as part of your request. If both the parties are agreed to share between, you can make it success
UPDATE:
Since your question is not explains what type of error, we assume and giving some answer
main.html
<div id="result"></div>
tableappend.html
<html>
<body>
<table id="myTable2" border="1">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<br>
</body>
</html>
In main.html
function myFunction()
{
//load the tableappend.html page, in the same site under same root
$("#result").load("tableappend.html table",
function(responseText, textStatus, XMLHttpRequest){
alert(textStatus) // should be success
}
}
I have a jQuery function I wrote which will slideToggle an additional table row. There is a cell at the end of the clickable row that contains a button, however as the click of a container div triggers the function, clicking anywhere in the row will cause the new row to expand.
I need the function to only be triggered when the button is clicked as there is scope to add checkboxes, links etc to other parts of the table.
Code:
var toggleSpeed = 600;
var expandText = "more";
var collapseText = "less";
$(".extrainfo_container").click(function() {
$(this).find('.extrainfo').slideToggle(toggleSpeed);
if ($(this).find('.moreless').text() == collapseText) {
$(this).find('.moreless').text(expandText)
}
else {
$(this).find('.moreless').text(collapseText);
}
});
<table>
<tr>
<td>Header 1</td>
<td>Header 2</td>
<td>Header 3</td>
</tr>
</table>
<div class="extrainfo_container">
<table>
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td><div class="moreless">more</div></td>
</tr>
<tr>
<td colspan="3">
<div class="extrainfo">
Extra information.<p />
Extra information.<p />
</div>
</td>
</tr>
</table>
</div>
Working example: http://jsfiddle.net/E22XR/69/
I have searched the forums, and although I did find similar questions and answers, none of them worked for me. I figure there must be something different I am doing, and/or there is a better way to achive the same result - I am quite new to writing my own functions.
If there is a better way, a requirement is that I do not use IDs as there could be any number of rows created dynamically.
You could do this I guess.
var toggleSpeed = 600;
var expandText = "more";
var collapseText = "less";
$(".moreless").click(function() {
$(".extrainfo_container").find('.extrainfo').slideToggle(toggleSpeed);
if ($(".extrainfo_container").find('.moreless').text() == collapseText) {
$(".extrainfo_container").find('.moreless').text(expandText)
}
else {
$(".extrainfo_container").find('.moreless').text(collapseText);
}
});
Edit : Hack for multiples rows
var toggleSpeed = 600;
var expandText = "more";
var collapseText = "less";
$(".moreless").click(function () {
var detailsRow = $(this).parent().parent().next();
detailsRow.find('.extrainfo').slideToggle(toggleSpeed);
if ($(this).text() == collapseText)
$(this).text(expandText);
else
$(this).text(collapseText);
});