Display and hide column in HTML by using Javascript - javascript

I am writing up an webpage to display a table with 2 columns and two rows(header and body).
I would like to control the show and hide of any of this 2 columns with Javacript.
The hide and display should be determined by the value of "input1" and"input2" from server.
If "input1"="empty"(string), hide colomn1(col1). Otherwise, display it.
Similar logic applying to "input2" and "col2"
I printed the value "input1" in the webpage and confirmed it is equal to "empty". However, the "col1" is still in the table displayed.
Can anyone point out the problem? If my approach is incorrect, please advise what is the best alternative.
<table>
<tr>
<th class="col1">Genus</th>
<th class="col2">Species</th>
</tr>
<tr>
<td class="col1">column1</td>
<td class="col2">column2</td>
</tr>
</table>
<script type="text/javascript">
function check()
{
if({{input1}}=="empty")
document.getElementByID("col1").style.display = "none";
else
document.getElementByID("col1").style.display = "block";
if({{input2}}=="empty")
document.getElementByID("col2").style.display = "none";
else
document.getElementByID("col2").style.display = "block";
}
</script>

I can see two big mistakes over there:
The method "getElementById" will not work since you're not selecting an element by its id, you're selecting it by its class. How to do that? I'll suggest you to download the jQuery library ( http://jquery.com/ ) and then search how to select elements by its class name. jQuery is, in some way, a javascript wrapper that will make your life much easier :)
Setting the "display" property to "none" should hide it, but setting if to "block" will probably screw the table up. You should either set it to "table-cell" or "table-header-group" depending on if it's td or th. I suggest you look at the documentation of the display property: http://www.w3schools.com/cssref/pr_class_display.asp
I hope it helped :)
EDIT: if you don't want to use jquery, check at this post: How to Get Element By Class in JavaScript?

Yes, it can be done. Here's a quick example: http://jsfiddle.net/vZB5k/
<body>
<table>
<tr>
<th class="col1">Genus</th>
<th class="col2">Species</th>
</tr>
<tr>
<td class="col1">
column1
</td>
<td class="col2">
column2
</td>
</tr>
</table>
<input type="button" id="hideCol1" value="Hide Column 1" />
<input type="button" id="hideCol2" value="Hide Column 2" />
<input type="button" id="hideBoth" value="Hide Both" />
<input type="button" id="showAll" value="ShowAll" />
<script>
var hideCol1 = function () {
var e = document.getElementsByClassName("col1");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
};
var hideCol2 = function () {
var e = document.getElementsByClassName("col2");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
};
var hideBoth = function () {
hideCol1();
hideCol2();
};
var showAll = function () {
var e = document.getElementsByClassName("col1");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "table-cell";
};
e = document.getElementsByClassName("col2");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "table-cell";
};
};
(function () {
document.getElementById("hideCol1").addEventListener("click", hideCol1);
document.getElementById("hideCol2").addEventListener("click", hideCol2);
document.getElementById("hideBoth").addEventListener("click", hideBoth);
document.getElementById("showAll").addEventListener("click", showAll);
})();
</script>
</body>
Updated - using "input" variables:
var hideCol1 = function () {
var e = document.getElementsByClassName("col1");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
};
var hideCol2 = function () {
var e = document.getElementsByClassName("col2");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
};
(function () {
if (input1 !== "on") {
hideCol1();
}
if (input2 !== "on") {
hideCol2();
}
})();

This should do the trick
<script>
function hideCol() {
if (document.getElementById("txt1").value != "") {
var elements = document.getElementsByClassName('col1')
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
}
if (document.getElementById("txt2").value != "") {
var elements = document.getElementsByClassName('col2')
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
}
}
</script>
check out this fiddle
update the code as per your requirement .. but it has code to select the elements to be hidden.
Edit 1
Here is the new fiddle
have made to work according to checkboxes
function hidecol() {
if (document.getElementById("txt1").checked) {
var elements = document.getElementsByClassName('col1')
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
}
if (document.getElementById("txt2").checked) {
var elements = document.getElementsByClassName('col2')
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
}
}
please let me know if this was helpful

Related

Laravel - Javascript CSS styling doesn't get applied even though code works in console

from highlights.js:
$(document).ready(function()
{
$("#myTable").tablesorter();
setAllDifferentHeight();
highlight();
}
);
function highlight()
{
var firsts = document.getElementsByClassName("first");
for(var i=0; i<firsts.length; i++){
firsts[i].style.backgroundColor = "gold";
}
var seconds = document.getElementsByClassName("second");
for(var i=0; i<seconds.length; i++){
seconds[i].style.backgroundColor = "silver";
}
var thirds = document.getElementsByClassName("third");
for(var i=0; i<thirds.length; i++){
thirds[i].style.backgroundColor = "brown";
}
var lasts = document.getElementsByClassName("last");
for (var i = lasts.length - 1; i >= 0; i--) {
lasts[i].style.backgroundColor = "pink";
}
}
from index.blade.php:
#foreach($student as $s)
<?php $sum = $s->mc+$s->tc+$s->hw+$s->bs+$s->ks+$s->ac; ?>
#if($sum == $first)
<tr class = "first">
#elseif($sum == $second)
<tr class = "second">
#elseif($sum == $third)
<tr class = "third">
#elseif($sum == $last)
<tr class = "last">
#endif
The HTML is generated with the right classes in the right places, but no highlighting is done by the javascript. When I run the Javascript code in the console, it does what I want it to. What is the issue here?

Disable table using checkbox

I have this checkbox, how to disable a table (disable all the input fields in the table) whenever I check the checkbox?
<label><input type="checkbox" name="view" value="d">N/A</label>
Is it possible using purely JavaScript and not jQuery.
This is the code now
var elems = document.getElementById('table-id').querySelectorAll('input,select,textarea');
document.getElementById('check').onchange = function () {
if (document.getElementById('check').checked) {
for (var i = 0; i < elems.length; i++) {
elems[i].disabled = true;
}
} else {
for (var i = 0; i < elems.length; i++) {
elems[i].disabled = false;
}
}
}
and the table
<table id='table-id' border="1">
but it shows error like this:
Uncaught TypeError: Cannot read property 'querySelectorAll' of null
Using jQuery, it is easy:
$("#tableId").find(":input").prop("disabled", true);
Using Javascript, it is a little longer:
var elems = document.getElementById('tableId').querySelectorAll('input,select,textarea');
for (var i = 0; i < elems.length; i++) {
elems[i].disabled = true;
}
Fiddle: http://jsfiddle.net/abhitalks/6s7QL/2/
Update:
Added your checkbox code:
document.getElementById('checkboxId').onchange = function () {...
Here is the pure JavaScript version to do the trick you want:
var table = document.getElementById('tableId'),
inputs = table.getElementsByTagName('input'),
checkbox = document.getElementById('checkboxId');
checkbox.onchange = function(e) {
if(checkbox.checked) {
disableTable(true);
} else {
disableTable(false);
}
}
function disableTable(disableState) {
for (var i = 0, l = inputs.length; i < l; i++) {
inputs[i].disabled = disableState;
}
}
And here is the working example in JSFiddle.

javascript change table rows background color dynamically for setinterval

I change the background of rows to dynamically for setinterval but not working.
if clicked the button, change class name as the rows in the table.
My codes:
HTML Code:
<table id="table">
<tr>
<td>AAA11</td>
<td>BBB11</td>
</tr>
..
..
</table>
<button id="btn">click</button>
CSS Codes
.red { background-color: red; }
JS Codes
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
// My func
function func(){
for (var i = 0; i < rows.length; i++) {
var index=0;
var c = rows[i].className;
if(c!="red") {
index=i;
} else {
index = i+1;
}
sec(index);
}
setInterval(func(), 2000);
}
// Change class name the rows
function sec(index){
for (var i = 0; i < rows.length; i++) {
if(index==i) {
rows[index].className="red";
}
if(index!=i ){
rows[index].className="null";
}
}
}
$('#btn').click(function(){
setInterval(func(), 2000);
});
you reset all other lines, except the last row with in the "sec" function.
if(index!=i ){
rows[index].className="null";
}
delete that part and it should work like you wanted
...tough i don't get what you want to do, since all you're doing is setting all rows backgrounds...if you want to reset the red ones, don't use your sec() function...try this instead:
function func(){
for (var i = 0; i < rows.length; i++) {
var index=0;
var c = rows[i].className;
if(c=="red") {
rows[i].className="";
} else {
rows[i].className="red";
}
}
}
[edit]
...after it's cleared what OP wanted to do:
http://jsfiddle.net/bzWV2/1/
[edit2]
...easier approach:
http://jsfiddle.net/bzWV2/2/
You could do something like that:
var $table = $("#table");
var $rows = $table.find("tr");
var func = function(){
var curIndex = $rows.filter('.red').index(),
nextIndex = curIndex === $rows.length - 1?0:++curIndex;
$rows.eq(nextIndex).addClass('red').siblings().removeClass('red');
}
$('#btn').click(function(){
$rows.eq(0).addClass('red');
setInterval(func, 2000);
});
DEMO
function highlight(element)
{
$('tr').removeClass('red');
el = (!element)? $('tr:first') : element;
el.addClass('red');
next_el = el.next('tr');
var el = (next_el.length == 0)? $('tr:first'): next_el;
setTimeout(function(){ highlight(el) }, 1000);
}
setTimeout(function(){ highlight() }, 1000);
http://fiddle.jshell.net/TFcUS/2/

Javascript for showing a div using the div's class name

I have a div in my page like that,
<div class="errormsg" style="display: none;">Username is empty</div>
i am having an input field like this,
<input type=textbox id="userid" />
Now i need a javascript for showing the error message div if input field was empty. I need to use the div class rather than id. Please help.
P.S : I don't want Jquery as my page has some restriction to use library files.
Try this, assuming only one errormsg div -
Update
I've added a fiddle here. Plus, there was a typo - corrected
<div class="errormsg" style="display: none;">Username is empty</div>
<input type=textbox id="userid" onchange="validate()" />
function validate(){
var userId = document.getElementById('userId'),
errorMsg = document.getElementsByClassName('errormsg').item();
if (userId.value === ''){
errorMsg.style.display = 'block'
} else {
errorMsg.style.display = 'none';
}
}
<div class="errormsg">Username is empty</div>
<input type='textbox' id="userid" onkeyup="javascript:call(this);" />
function getElementsByClassName(className) {
// For IE
if (document.all) {
var allElements = document.all;
} else {
var allElements = document.getElementsByTagName("*");
}
var foundElements = [];
for (var i = 0, ii = allElements.length; i < ii; i++) {
if (allElements[i].className == className) {
foundElements[foundElements.length] = allElements[i];
}
}
return foundElements;
}
function call(control)
{
var userid=document.getElementById('userid');
var errorMsg = getElementsByClassName('errormsg')[0];
if(userid.value == '')
{
errorMsg.style.display = "block";
}
else
{
errorMsg.style.display = "none";
}
}
Removed the JQuery and added the Javascript code as below:
<div class="errormsg">Username is empty</div>
<input type='textbox' id="userid" onkeyup="javascript:call(this);" />
function getElementsByClassName(className) {
// For IE
if (document.all) {
var allElements = document.all;
} else {
var allElements = document.getElementsByTagName("*");
}
var foundElements = [];
for (var i = 0, ii = allElements.length; i < ii; i++) {
if (allElements[i].className == className) {
foundElements[foundElements.length] = allElements[i];
}
}
return foundElements;
}
function call(control)
{
var userid=document.getElementById('userid');
var errorMsg = getElementsByClassName('errormsg')[0];
if(userid.value == '')
{
errorMsg.style.display = "block";
}
else
{
errorMsg.style.display = "none";
}
}

Hiding columns in table JavaScript

This script stops working the moment I add a table inside a table, so how to get it worked?
I don't need any jQuery solutions, I want pure JavaScript. Here's my script found on the Internet:
<script>
function show_hide_column(col_no, do_show) {
var stl;
if (do_show) stl = 'block'
else stl = 'none';
var tbl = document.getElementById('id_of_table');
var rows = tbl.getElementsByTagName('tr');
for (var row=1; row<rows.length;row++) {
var cels = rows[row].getElementsByTagName('td')
cels[col_no].style.display=stl;
}
}
</script>
Here's my HTML:
<table id='id_of_table' border=1>
<tr><td colspan="4"><table><tr><td></td></tr></table></td></tr>
<tr><td> 2</td><td> two</td><td> deux</td><td> zwei</td></tr>
<tr><td> 3</td><td> three</td><td> trois</td><td> drei</td></tr>
<tr><td> 4</td><td> four</td><td>quattre</td><td> vier</td></tr>
<tr><td> 5</td><td> five</td><td> cinq</td><td>fünf</td></tr>
<tr><td> 6</td><td> six</td><td> six</td><td> sechs</td></tr>
</table>
And here's my Form:
<form>
Enter column no: <input type='text' name=col_no><br>
<input type='button' onClick='javascript:show_hide_column(col_no.value, true);' value='show'>
<input type='button' onClick='javascript:show_hide_column(col_no.value, false);' value='hide'>
</form>
You can leverage the col tag and then the solution is straightforward using only vanilla JavaScript. The col tag has only a few CSS attributes, but visibility is one of them:
function show_hide_column( col_no, do_show ){
const table = document.getElementById( 'id_of_table' )
const column = table.getElementsByTagName( 'col' )[col_no]
if ( column ){
column.style.visibility = do_show?"":"collapse";
}
}
const btnHide = document.getElementById( 'btnHide' )
btnHide.addEventListener( "click", () => show_hide_column( 2, false ))
const btnShow = document.getElementById( 'btnShow' )
btnShow.addEventListener( "click", () => show_hide_column( 2, true ))
<table id='id_of_table' border=1>
<col class="col1"/>
<col class="col2"/>
<col class="col3"/>
<col class="col4"/>
<tr><td colspan="4"><table><tr><td></td></tr></table></td></tr>
<tr><td> 2</td><td> two</td><td> deux</td><td> zwei</td></tr>
<tr><td> 3</td><td> three</td><td> trois</td><td> drei</td></tr>
<tr><td> 4</td><td> four</td><td>quattre</td><td> vier</td></tr>
<tr><td> 5</td><td> five</td><td> cinq</td><td>fÜnf</td></tr>
<tr><td> 6</td><td> six</td><td> six</td><td> sechs</td></tr>
</table>
<button id="btnHide">hide French</button>
<button id="btnShow">show French</button>
References:
col
visibility on quirksmode
You could use children and check their tagName to make sure they're td's. Something like this:
function show_hide_column(col_no, do_show) {
var tbl = document.getElementById('id_of_table');
var rows = tbl.getElementsByTagName('tr');
for (var row = 0; row < rows.length; row++) {
var cols = rows[row].children;
if (col_no >= 0 && col_no < cols.length) {
var cell = cols[col_no];
if (cell.tagName == 'TD') cell.style.display = do_show ? 'block' : 'none';
}
}
}
Edit: Here's a working example: http://jsfiddle.net/3DjhL/2/.
Edit:
In fact, I've just remembered the rows and cols properties, which make it even simpler. See http://jsfiddle.net/3DjhL/4/ to see it in action.
function show_hide_column(col_no, do_show) {
var rows = document.getElementById('id_of_table').rows;
for (var row = 0; row < rows.length; row++) {
var cols = rows[row].cells;
if (col_no >= 0 && col_no < cols.length) {
cols[col_no].style.display = do_show ? '' : 'none';
}
}
}
Oh, and if you think the column numbers should start at 1 (which they don't), you'll have to offset that somewhere. For example at the top of show_hide_column():
col_no = col_no - 1;
The important thing here is the selector, it could be vanilla or jquery:
document.querySelectorAll('#yourtable tbody tr td:nth-child(1)').forEach(el=>el.style.display = 'none')
From the code above, the nth-child(1) selector has a 1-based index, there you define the column you want to hide ;)
I had a situation where it would have been a very big hassle to modify every single TD value and add the appropriate class name so I could toggle it. As a result I wrote some JavaScript to do that automatically. Please see the following code.
tbl = document.getElementById("Mytable")
classes = getClasses(tbl.rows[0]);
setClasses(tbl, classes);
toggleCol("col0");
toggleCol("col1");
function getClasses(row){
var cn = 0;
var classes = new Array();
for(x=0; x < row.cells.length; x++){
var cell = row.cells[x];
var c = new Column(cell.textContent.trim(), cell.offsetLeft, cell.offsetLeft + cell.offsetWidth, x);
classes[x]= c;
}
return classes;
}
function Column(name, left, right, cols) {
this.name = name;
this.left = left;
this.right = right;
this.cols = cols;
}
function setClasses(table, classes){
var rowSpans = new Array();
for(x=0; x < table.rows.length; x++){
var row = table.rows[x];
for(y=0; y < row.cells.length; y++){
var cell = row.cells[y];
for(z=0; z < classes.length; z++){
if(cell.offsetLeft >= classes[z].left && cell.offsetLeft <= classes[z].right){
cell.className = "col" + classes[z].cols;
}
}
}
}
}
function toggleCol(name){
var cols = document.getElementsByClassName(name);
for(x=0; x < cols.length; x++){
cols[x].style.display= (cols[x].style.display == 'none') ? '' : 'none';
}
}
In my example I take a look at the first row to set the top level header (In my example I had several who had colspans). It uses the offsetLeft and offsetWidth to determine the range of the top header (which in my cases has sub headers), so that all sub-columns would toggle with its parent.
Based on these values setClasses sets the appropriate classes to all the elements.
In my example I then toggle "col0" and "col1", so they would be invisible (Running the function again would make them visible again).

Categories