Show/hide tables with jQuery - javascript

I have a series of tables similar to the following html code:
<table id="film"><tr>
<th class="1">//HEAD CONTENT 1//</th>
</tr>
<tr>
<td class="1">//BODY CONTENT 1//</td>
</tr></table>
<table id="film"><tr>
<th class="2">//HEAD CONTENT 2//</th>
</tr>
<tr>
<td class="2">//BODY CONTENT 2//</td>
</tr></table>
I want the tables to expand individually when the respective head (<th>) is clicked. Moreover the tables should start unexpanded. I use the following jQuery script:
$(document).ready(function(){
$('#film td').hide();
});
$(document).ready(function(){
var n1 = 0;
$('#film th.1').click(function(){
if(n1 == 0){
$('#film td.1').show();
n1 = 1;
}else{
$('#film td.1').hide();
n1 = 0;}
});
var n2 = 0;
$('#film th.2').click(function(){
if(n2 == 0){
$('#film td.2').show();
n2 = 1;
}else{
$('#film td.2').hide();
n2 = 0;}
});
});
However when I execute only the top table is able to show/hide not the second one.
Can anyone see where I'm going wrong?

You are using the same id on multiple elements. When you search by id, jQuery will only return one item (the first with that id). So your code is only acting on the first table. Use a class on the tables instead of an id.
<table class="film">......</table>
$('.film').each(function(f) {
//this function will execute for each element with the class "film"
//refer to the current element during this function using "$(this)"
});

A much easier way to do this is to use a class instead of an id for the table values. This way they can be referred to as a group more easily
<table class="film"> ...
After which the following jquery should give you the behavior you're looking for
$(document).ready(function() {
$('.film td').hide();
$('th').click(function() {
$(this).parents('table').find('td').toggle();
});
});
Fiddle: http://jsfiddle.net/WZUAZ/1/

Here is a working version: http://jsfiddle.net/6Ccj7/
Your html is broken. Change this:
<td class"2">//BODY CONTENT 2//</td>
To this:
<td class="2">//BODY CONTENT 2//</td>
Also, you used id for film when in fact you have 2 instances. You class instead:
<table class="film"><tr>
<th class="1">//HEAD CONTENT 1//</th>
</tr>
<tr>
<td class="1">//BODY CONTENT 1//</td>
</tr></table>
<table class="film"><tr>
<th class="2">//HEAD CONTENT 2//</th>
</tr>
<tr>
<td class="2">//BODY CONTENT 2//</td>
</tr></table>
Here is the updated JS:
$(document).ready(function(){
$('.film td').hide();});
$(document).ready(function(){
var n1 = 0;
$('.film th.1').click(function(){
if(n1 == 0){
$('.film td.1').show();
n1 = 1;
}else{
$('.film td.1').hide();
n1 = 0;}
});
var n2 = 0;
$('.film th.2').click(function(){
if(n2 == 0){
$('.film td.2').show();
n2 = 1;
}else{
$('.film td.2').hide();
n2 = 0;}
});
});

Two problems:
First, Your HTML is broken
Change
<td class"2">//BODY CONTENT 2//</td>
To
<td class="2">//BODY CONTENT 2//</td>
Second, HTML id's should be unique so I suggest using classes instead.
Here is a working example: http://jsfiddle.net/jkohnen/tBkh4/
I used .toggle() to simplify the jQuery a bit
Hope that helps, and Happy Coding.

show/hide table with jquery
Code here !
i'm useslideToggle + data attr

Using this jQuery you can show & hide
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
html
<button id="hide">Hide</button>
<button id="show">Show</button>

Related

How to change color of my div if check-box is checked?

I have table that is created based on records from data base. Inside of tbody I have tr that creates each table row. Table row has multiple time slots for same date. I want to change background color of my time block if check box is checked. I got my check box to work, I did test with alert and some text inside. Now I'm trying to change the background color but nothing works in this case that I tried so far. Here is my code:
<cfoutput query="qryTest" group="DateMeeting">
<tbody>
<tr>
<td>#DateMeeting#</td>
</tr>
<cfoutput>
<tr class="blockRow">
<td>#StartTime#</td>
<td>#EndTime#</td>
<td><input type="checkbox" name="block" id="block"></td>
</tr>
</cfoutput>
</tbody>
</cfoutput>
Java script:
$('input[type=checkbox]').on('change', function() {
var div = $(this).closest('.blockRow');
$(this).is(":checked") ? div.addClass("red") : div.removeClass("red");
});
and my css:
.red{
background-color:red;
}
This is working code that I updated. Problem number one was in html structure of my code. Second If I used document.getElementById('') I was getting only first row chnaged background-color, no matter which row I click on. So I have had to use getElementByClassName. Anyway I decided to use JQuery addClass/removeClass. Thanks everyone for help with this problem.
Try this:
$('input[type=checkbox]').on('change', function() {
var div = $(this).closest('.blockRow');
$(this).is(":checked") ? div.addClass("red") : div.removeClass("red");
});
.red{
background-color:red;
}
<cfoutput query="qryTest" group="DateMeeting">
<tbody>
<tr>
<td>#DateMeeting#</td>
<cfoutput>
<div class="blockRow">
<td>#StartTime#</td>
<td>#EndTime#</td>
<td><input type="checkbox" name="block" id="block"></td>
</div>
</cfoutput>
</tr>
</tbody>
</cfoutput>
jsfiddle:
https://jsfiddle.net/3s83gj70/2/
This gets the closest blockrow to the current checkbox so should work with more than one instance. Since you can't have 2 elements with the same id I have change blockrow to the class.
If you want to do other things based on the same condition then you can do this:
$('input[type=checkbox]').on('change', function() {
var div = $(this).closest('.blockRow');
if($(this).is(":checked")){
div.addClass("red");
//checkbox is checked, do something
}
else
{
div.removeClass("red");
//checkbox is not checked, do something else
}
});
Easy:
$('#blockRow').css("background-color","red")
------------------------------^
EDIT
Then you don't include jQuery library. To make pure js make this:
http://jsfiddle.net/bfss81sa/
document.getElementById("box").style.backgroundColor = "red";
Here you are the complete snippet:
var cbs = document.querySelectorAll('input[type=checkbox]');
for(var i = 0; i < cbs.length; i++) {
cbs[i].addEventListener('change', function() {
if(this.checked) {
document.getElementById("box").style.backgroundColor = "red";
} else {
document.getElementById("box").style.backgroundColor = "transparent";
}
});
}
<input type="checkbox" name="block" id="block">
<div id="box">
The box
</div>
Your html code is a mess. Anyway, generally :
$('input[type=checkbox]').click(function() {
if($(this).is(':checked') {
$(this).parents('tr').find('td:first').css('background', 'red');
} else {
$(this).parents('tr').find('td:first').css('background', 'white');
}
});
Of course, you can narrow the scope of input:checkbox selector.
If it is not the FIRST <td> in your <tr> then you better assign it a class and get it with it.
NOTE : DOM must be correct <cfoutput> cannot be child of <tr>; <div> cannot have <td> as direct child; Incorrect DOM impact javascript traversing.

javascript get external table row on click

I have a button:
<button id="external-list-row">Test</button>
in which I would like to change with a row from an external table on click. The external table is structured like this;
<table id="table_id">
<thead>
<tr>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>Row 1</p>
</td>
</tr>
<tr>
<td>
<p>Row 2</p>
</td>
</tr>
<tr>
<td>
<p>Row 3</p>
</td>
</tr>
</tbody>
</table>
So my question is this; how can I replace "Test" in the button with the content of Row 1 with javascript?
As for the javascript, I'm not sure how I can get the content from row 1, and replace the button with it.
<script>
var rows = document.getElementById('table_id').getElementsByTagName("tr");
for (var i=0; i<rows.length; i++) {
$('#external-list-row').onclick = function() {
}};
</script>
Post comments:
I can access table data from other tables within the same html file, but I still don't know how to access data from tables in other html files. For example, if I try to access a videos liquid file from another liquid file, like photos, nothing happens when I press the button.
Fiddle of current code. It can replace the content of a list with the content of another, but the lists need to be on the same html file.
https://jsfiddle.net/hgnymydL/
Well, the first thing you should understand, is that a table element has a rows property, so getting the first row is trivial.
var table = document.getElementById("table_id");
var firstRow = table.rows[0];
From there, you can use textContent to get the text content of the row. I believe that's what you were looking for.
You can also select the first row of a table with a CSS selector like so:
var firstRow = document.querySelector("#table_id tbody tr");
$('#external-list-row').on('click', function() {
$(this).text($('#table_id tbody tr:first').text());
});
If you want to replace the button text with contents of the First Row ONLY then:
$('#external-list-row').html($('tr:first-child').html);
Of course you could wrap this in any event, so for example, on clicking the button:
$('#external-list-row').on('click', function() {
$(this).html($('tr:first-child').text());
});
BUT, based on the code you have given, I'm assuming you want to change the text after each click in which case you could do this:
var clickNumber = -1;
$('#external-list-row').on('click', function(event) {
clickNumber = clickNumber + 1;
//console.log('\n\nclickNUmber' + clickNumber);
$('tbody tr').each(function(index, el) {
//console.log('index: ' + index);
var block = $(el).find('td p');
if(index == clickNumber) {
//console.log('entered if')
//console.log(block.text());
//console.log('----clickNUmber' + clickNumber);
//console.log('index: ' + index);
//console.log(el);
$('#external-list-row').html(block.text());
}
});
});
jsFiddle: https://jsfiddle.net/zmb2b37t/
Hope that helps!
If you are wanting to replace the visible text "Test" in the button with the content of the cell clicked:
var tbl = document.getElementById('table_id');
var btn = document.getElementById('external-list-row');
tbl.onclick = function(ev){
var trgt = ev.target;
if(trgt.tagName === 'P' ||trgt.tagName === 'TD'){
btn.textContent = trgt.textContent;
}
};
Only one event handler is attached in this scenario.
Via event delegation we determine if it was a TD or P element that was clicked. If the rows are modified the function will still work.
Here is jquery code of do this
$('#table_id tr td').on('click', function(){
$('#external-list-row').html($(this).html());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="external-list-row">Test</button>
<table id="table_id">
<thead>
<tr>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>Row 1</p>
</td>
</tr>
<tr>
<td>
<p>Row 2</p>
</td>
</tr>
<tr>
<td>
<p>Row 3</p>
</td>
</tr>
</tbody>
</table>

Fetch content of next td on checkbox click

How to fetch the content of the next td when the check box is clicked
<table>
<tr>
<td>
<input type=checkbox name=t>
</td>
<td width=25%>
FOOBAR
</td>
<td width=73%>
BAZ
</td>
</tr>
<tr>
<td>
<input type=checkbox name=t>
</td>
<td width=25%>
FOO
</td>
<td width=73%>
BAR
</td>
</tr>
</table>
My javascript code:
var c=new Array();
c=window.document.getElementsByTagName('input');
for(var i=0;i<c.length;i++)
{
if(c[i].type=='checkbox')
{
alert(c[i].parentNode.parentNode.rows[0].innerHTML);
}
}
I am trying to fetch the content of the next td when a check box is clicked. For the first row, FOOBAR should be fetched and so on.
EDIT
POINTS TO NOTE: I'm pretty sure about the tags that I am using for
this question. Please dont post any answers that point to some JS
library eg. jQuery etc.
This seems to work, though it's very HTML-dependant (as is much JavaScript that involves DOM-traversal, of course):
var c = [];
c = window.document.getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].onchange = function() {
if (this.checked){
console.log(this.parentNode.nextElementSibling.firstChild.nodeValue.trim());
}
};
}
}​
JS Fiddle demo.
References:
firstChild.
`nextElementSibling.
nodeValue.
parentNode.
trim().
I have used jQuery. I am guessing that's alright?
​$('input:checkbox').live('click', function() {
alert($(this).parent().next('td').text());
});​​​​​​​​​​​​​​​
http://jsfiddle.net/6Mwqz/
Use jQuery, will be better, here your solution:
$('[type=checkbox]').on('click', function(){
var html;
if($(this).is(':checked')) {
html = $(this).parent().next('td').html();
alert(html);
}
});
​
DEMO: http://jsfiddle.net/oscarj24/yYuzS/

Issue related to getting class name in jquery

I have the following HTML:
<table id="ChatTable" class="ChatBox" style="margin-left:0px !important">
<tr class="row1">
<td></td>
</tr>
<tr class="row2">
<td></td>
</tr>
</table>
and the following jQuery :
<script>
$(document).ready(function () {
var Tabletr= $(".ChatBox > tbody > tr:odd");
});
</script>
how can i get the class name of Odd row in Jquery?
Simply
var $elems = $("table.ChatBox tr:odd"); should work.
To get their classes(heads up to Juicy Scripter below),
$elems.each(function(){ console.log(this.className); //do whatever with the class names. });
Try this:
<script>
$(document).ready(function () {
var Tabletr= $(".ChatBox").children("td:odd").attr("class");
alert (Tabletr);
}
});
</script>
You can also use :first instead of :odd if you wish to get the first td class.
jQuery itself doesn't provide direct way to retrieve DOM element class other than using attr method of jQuery or className property for element in JavaScript after you get the elements:
$(document).ready(function () {
var Tabletr= $(".ChatBox > tbody > tr:odd");
var firstElementClass = Tabletr.eq(0).attr('class');
// Previous is the same as
var firstElementClass = Tabletr.get(0).className;
// Due to fact that Tabletr may contain more that one row you may want to iterate and collect classes names.
var classes = [];
Tabletr.each(function(){
classes.push(this.className);
// OR
classes.push($(this).attr('class'));
});
});
You can simplify your selector:
var Tabletr = $(".ChatBox tr:odd")
This gives you a jQuery object for each odd row in your table. If there's just one such row, you could do this:
var Tabletr = $('.ChatBox tr:odd')[0].className; // -> "row2"
But if there are multiple rows, you need something more like this:
var TableRowClasses = $(".ChatBox tr:odd").map( function(){
return this.className;
}).get();
This gives you an array with every odd row's class as an element. So you'd end up with an array like this:
["row2","row4","row6"] // confusing odd-row classnames notwithstanding
I've look at your code and the following changes gave me the result your after.
<table id="ChatTable" class="ChatBox" style="margin-left:0px !important">
<tr class="row1">
<td></td>
</tr>
<tr class="row2">
<td></td>
</tr>
<tr class="row3">
<td></td>
</tr>
<tr class="row4">
<td></td>
</tr>
</table>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
$(".ChatBox tr:odd").each(function () {
//test
alert($(this).attr("class"));
});
});
</script>

How to add hyperlink to table row <tr>

I am having a table with its table row <tr> generating in a loop to form multiple rows.
I want to give separate <a> link to each <tr>. Since in table we can add only add data to <td> only, I am not able to achieve that.
Is there any other way to achieve this?
Html:
<table>
<tr href="http://myspace.com">
<td>MySpace</td>
</tr>
<tr href="http://apple.com">
<td>Apple</td>
</tr>
<tr href="http://google.com">
<td>Google</td>
</tr>
</table>
JavaScript using jQuery Library:
$(document).ready(function(){
$('table tr').click(function(){
window.location = $(this).attr('href');
return false;
});
});
You can try this here: http://jsbin.com/ikada3
CSS (optional):
table tr {
cursor: pointer;
}
OR the HTML valid version with data-href instead of href:
<table>
<tr data-href="http://myspace.com">
<td>MySpace</td>
</tr>
<tr data-href="http://apple.com">
<td>Apple</td>
</tr>
<tr data-href="http://google.com">
<td>Google</td>
</tr>
</table>
JS:
$(document).ready(function(){
$('table tr').click(function(){
window.location = $(this).data('href');
return false;
});
});
CSS:
table tr[data-href] {
cursor: pointer;
}
Playing off of #ahmet2016 and keeping it W3C standard.
HTML:
<tr data-href='LINK GOES HERE'>
<td>HappyDays.com</td>
</tr>
CSS:
*[data-href] {
cursor: pointer;
}
jQuery:
$(function(){
$('*[data-href]').click(function(){
window.location = $(this).data('href');
return false;
});
});
The easiest way I've found to turn a table row into a link is to use the onclick attribute with window.location.
<table>
<tr onclick="window.location='/just/a/link.html'">
<td></td>
</tr>
</table>
I agree with the first response, more information is needed. But if you're just trying to make a table of links, you can just do
<tr><td>...</td></tr>
If you're saying that you want to make each <tr> clickable, you can add a click event to each <tr>, or better yet, add a .delegate() handler to the table that manages clicks on its <tr> elements.
$('#myTable').delegate('tr','click',function() {
alert( 'i was clicked' );
});
This code assumes your table has the myTable ID:
<table id="myTable">
<tr><td> cell </td></tr>
<tr><td> cell </td></tr>
</table>
If this isn't what you meant, then please clarify your question, and post the relevant javascript code you're using.
PHP:
echo "<tr onclick=\"window.location='".$links[$i]."'\">......";
Javascript without jQuery:
x=1;
.
.
for (...) {
var tr=document.createElement('tr');
tr.onclick=function() { window.location='page'+(x++)+'.html'}
tr.style.cursor='pointer';
.
}
will let the user click on each row
you can use an array to load the pages too:
x=0;
var pages=["pagea.html","pageb.html"]
.
.
for (...) {
var tr=document.createElement('tr');
tr.onclick=function() { window.location=page[x++];}
tr.style.cursor='pointer';
.
}
The premium suggestion would be to add the tags when you generate the table. If you need to do it after the table is rendered and you want to use javascript you can always add something like
var mytable = document.getElementById("theTable")
var myrows = mytable.rows
for(i=0;i < myrows.length;i++)
{
var oldinner;
oldinner = myrows[i].cells[0].innerHTML;
myrows[i].cells[0].innerHTML = "<a>" + oldinner + "</a>";
}
or if you need to do it to every cell, your can always
var mytable = document.getElementById("theTable")
var myrows = mytable.rows
for(i=0;i < myrows.length;i++)
{
mycells = myrows[i].cells;
for(a=0;a < mycells.length;a++)
{
var oldinner;
oldinner = mycells[a].innerHTML;
mycells[a].innerHTML = "<a>" + oldinner + "</a>";
}
}
I hope you find this helpful
<tr><td><a></a></td></tr>
this?
jQuery.wrap the returned anchor to a td and then add to tr and jQuery.appendTo table
$('ith anchor element in array').wrap('<td />').wrap('<tr />').appendTo('table#table_id');
You can simply gen the with and inside as Nicole suggested:
<tr><td>title of the url</td></tr>
Or put the url in the tr tag like
With jQuery included
$('tr.clickable').click(function(){
window.location = $(this).attr("title");
});
to bring you to that page on click (basically hacking a tr to work like a tag (just a thought, never really try it.
add in
and change display style to display:block
and add same size for like this:
CSS:
#Table a {
display:block;
}
#Table td {
width:100px;
hright:100px
}
HTML:
<table id="Table">
<tr><td><a onclick="" href="#"> cell </a></td></tr>
<tr><td> cell </td></tr>
</table>
You can use data-href script to add href in any html elements. It makes html valid since it add only data-href attribute to a element.
https://github.com/nathanford/data-href/

Categories