I have a long table with many many columns and it looks really ugly for the users. What I wanted to do was create a simple button that would act as a switch, to turn on and off some of the columns.
Some of the columns are not needed, so what I did was add a class to every that wasn't needed, eg: ....
Now, what I thought I could do was this:
var hidden = 1;
function toggleTable(){
element_array = document.getElementsByClassName('disabled');
for(i = 0; i < element_array.length; i++){
if(hidden == 1){
element_array[i].style.display = 'none';
}else{
element_array[i].style.display = '';
}
}
if(hidden == 1) hidden = 0;
else hidden = 1;
}
This works for the most part in Firefox, but some quick tests in IE(7+8) and I get the following:
Message: Object doesn't support this property or method
Obviously indicating that IE doesn't want to let me simply change "display: none;" for something like table columns/rows.
I can't think of any workarounds. Ideally I'd like a fully cross-compatible solution to toggling the display of certain table columns,but if it's not compatible in the older browsers (eg: IE6) then that would also be OK.
The error that you're getting is not because IE doesn't want to set the display property, it's because the getElementsByClassName method isn't implemented in IE. If you want an implementation of that methods you can use this one which was written by Dustin Diaz.
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
Then you would re-write your method as follows.
var hidden = 1;
function toggleTable(){
var element_array = getElementsByClass('foo');
for(i = 0; i < element_array.length; i++){
if(hidden == 1){
element_array[i].style.display = 'none';
}else{
element_array[i].style.display = '';
}
}
if(hidden == 1) hidden = 0;
else hidden = 1;
}
toggleTable();
And what about jQuery.toggle()?
$(".disabled").toggle();
Related
In a GridView, the name of the table is getting generated dynamically. but it will have the dynamic Name with GridView ID gets appended.
something Like "w123443dsfnsbd32dkkd_GridView1". so first part will always keep changing whenever we reloads the grid. so I would like to get the name of the Grid with "_GridView1", with this I would like to fetch the complete Grid Name. So Is there a way to look for this?
I tried this var table = document.getElementById("GridView1"); but didn't work.
Code:
var table = document.getElementById("wcwidget_df5339c463eedb_widget_gridView1");
if (table.rows.length > 0) {
for (var i = 0 ; i < table.rows.length; ++i) {
if (table.rows[i].cells[0].innerText == "Company1" || table.rows[i].cells[0].innerText == "Company2" ||
table.rows[i].cells[0].innerText == "Company5" )
{
for (var k = 1; k < table.rows[i].cells.length; ++k) {
table.rows[i].cells[k].style.fontWeight = "bold";
table.rows[i].cells[k].style.color = "black";
}
}
}
for (var i = 0 ; i < table.rows.length; ++i) {
if (table.rows[i].cells[0].innerText == "Risk" || table.rows[i].cells[0].innerText == "Medium Risk" || table.rows[i].cells[0].innerText == "High Risk" ) {
table.rows[i].cells[0].style.fontWeight = "bold";
table.rows[i].cells[0].style.color = "black";
}
}
}
try this:
document.querySelectorAll("[id*='GridView1']")
this will return an array.
On modern browsers see the #amit's answer.
If compatibility with older browsers is required:
var allElements = document.getElementsByTagName("*");
for (var i = 0, n = allElements.length; i < n; ++i) {
var element = allElements[i];
if (element.id.endsWith("_GridView1")) {
// do something with the found element
break;
}
}
I am trying to use <label> elements in my html contact form like the HTML5 placeholder attribute for inputs. I have written the following JavaScript to to act as a reusable function witch will provide the following functionality.
Find the input by name.
Get the value of the input.
Find the label belonging to the input.
Change the label style depending on the state of the input.
Change the label style depending on the value of the input.
However it is not working and I don't know why as no errors appear in the console. What am I doing wrong? here is a JS Fiddle with code
function placeholder(field_name) {
// Get the input box with field_name
// Then get input value
var box = document.getElementsByName(field_name);
var i;
for (i = 0; i < box.length; i++) {
var value = document.getElementById(box[i].value);
}
// Get the labels belonging to each box using the HTML for attribute
var labels = document.getElementsByTagName('LABEL');
for (i = 0; i < labels.length; i++) {
if (labels[i].htmlFor !== '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem) {
box.label = labels[i];
}
}
}
// Colors
var focusColor = "#D5D5D5";
var blurColor = "#B3B3B3";
// If no text is in the box then show the label grey color
box.onblur = function () {
box.label.style.color = blurColor;
};
// If input focuses change label color to light grey
box.onfocus = function () {
box.label.style.color = focusColor;
};
// If there is text in the box then hide the label
if (box.value !== "") {
// Quick do something, hide!
box.label.style.color = "transparent";
}
}
// Call the function passing field names as parameters
placeholder(document.getElementsByName("email"));
placeholder(document.getElementsByName("firstName"));
placeholder(document.getElementsByName("lastName"));
This might be considered a little overkill on the number of listeners I've used, feel free to remove any you think unnecessary, but I've tried to employ your HTML structure as you have it and give you all desired effects. It should work for either the <label>s for matching the <input>s id OR matching it's <name> (given no id matches). I'll always say prefer using an id over name. I believe this JavaScript should also work in all browsers too, except the addEventListener for which you'd need a shim for old IE versions (let me know if it doesn't in one/the error message).
Demo
var focusColor = "#D5D5D5", blurColor = "#B3B3B3";
function placeholder(fieldName) {
var named = document.getElementsByName(fieldName), i;
for (i = 0; i < named.length; ++i) { // loop over all elements with this name
(function (n) { // catch in scope
var labels = [], tmp, j, fn, focus, blur;
if ('labels' in n && n.labels.length > 0) labels = n.labels; // if labels provided by browser use it
else { // get labels from form, filter to ones we want
tmp = n.form.getElementsByTagName('label');
for (j = 0;j < tmp.length; ++j) {
if (tmp[j].htmlFor === fieldName) {
labels.push(tmp[j]);
}
}
}
for (j = 0; j < labels.length; ++j) { // loop over each label
(function (label) { // catch label in scope
fn = function () {
if (this.value === '') {
label.style.visibility = 'visible';
} else {
label.style.visibility = 'hidden';
}
};
focus = function () {
label.style.color = focusColor;
};
blur = function () {
label.style.color = blurColor;
};
}(labels[j]));
n.addEventListener('click', fn); // add to relevant listeners
n.addEventListener('keydown', fn);
n.addEventListener('keypress', fn);
n.addEventListener('keyup', fn);
n.addEventListener('focus', fn);
n.addEventListener('focus', focus);
n.addEventListener('blur', fn);
n.addEventListener('blur', blur);
}
}(named[i]));
}
};
placeholder("email"); // just pass the name attribute
placeholder("firstName");
placeholder("lastName");
http://jsfiddle.net/cCxjk/5/
var inputs = document.getElementsByTagName('input');
var old_ele = '';
var old_label ='';
function hide_label(ele){
var id_of_input = ele.target.id;
var label = document.getElementById(id_of_input + '-placeholder');
if(ele.target == document.activeElement){
label.style.display = 'none';
}
if (old_ele.value == '' && old_ele != document.activeElement){
old_label.style.display = 'inline';
}
old_ele = ele.target;
old_label = label;
}
for(var i = 0; i < inputs.length; i++){
inputs[i].addEventListener('click', hide_label);
}
I will point out a couple things, you will have to find away around the fact that the label is inside the input so users now can't click on half of the input and actually have the input gain focus.
Also I guess you want to do this in IE (otherwise I would strongly advise using the html5 placeholder!) which means you would need to change the ele.target to ele.srcElement.
I am new to javascript and for practice, I am using javascript to stripe even rows for tables with a particular class. Besides that, I am trying to create a 'hover' effect on table rows using javascript only.
I was able to create the onmouseover effect, however, I am having a very difficult time going back to the default style onmouseout of the table row.
Please keep in mind that I know this can easily be achieved with css or JQuery; however, for this, I would like to stick to javscript only.
What I tried:
function alternate(){
var tables = document.getElementsByTagName("table");
//apply the code to ALL tables on the page with a particular class
for (var ti = 0; ti < tables.length; ++ti) {
if (tables[ti].className == "striped"){ //stripe tables
var rows = tables[ti].getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//change style of even rows to create striped effect
if(i % 2 == 0){
rows[i].className += "even"; //stripe even rows while maintaining default style to odd rows
}
rows[i].onmouseover = function() {
this.className="";
this.className="hovered";
}
rows[i].onmouseout = function() {
if(i % 2 == 0){
this.className="even";
}else{
this.className="odd";
}
}
}
}
}
}
I'm not sure if I quite understood your question, but I have created a jsfiddle which does what I think you meant.
The problem, from what I could tell, was that when row[i].mouseout is triggered, the value of i is the number of tables rows in your table. The fix is, to save the original classname on mouseover, and then re-assign that classname onmouseout. Here is the fiddle. http://jsfiddle.net/LBaZu/4/
function alternate() {
var tables = document.getElementsByTagName("table");
for (var ti = 0; ti < tables.length; ++ti) {
if (tables[ti].className == "striped") {
var rows = tables[ti].getElementsByTagName("tr");
var cls; // Variable to save the className
for (var i = 0; i < rows.length; i++) {
if (i % 2 == 0) rows[i].className = "even";
rows[i].onmouseover = function() {
cls = this.className; // Assign the className here
this.className = "hovered";
}
rows[i].onmouseout = function() {
this.className = (cls == 'even') ? cls : 'odd';
}
}
}
}
}
Edit: I re-read your question and it occurred to me that you only wanted to set the odd table rows classname to odd on mouseout, not before.
I have text on a page, its in a <h3> tag, which has a class ms-standardheader, but there are other texts on the page with the same class in its own <h3> tag. I also know the text I want to hide is 'Session'.
With this how can I write a javascript function to hide only this text?
Here is an image of the developtools from IE.
I'd suggest, if you're restricted (as your tags suggest) to non-library plain JavaScript, the following:
var h3s = document.getElementsByTagName('h3'),
classedH3 = [];
for (var i = 0, len = h3s.length; i < len; i++) {
if (h3s[i].className.indexOf('ms-standardheader') > -1) {
classedH3.push(h3s[i]);
}
}
for (var i = 0, len = classedH3.length; i < len; i++) {
if (classedH3[i].firstChild.nodeValue == 'the text to hide'){
classedH3[i].style.display = 'none';
}
}
JS Fiddle demo.
References:
push().
document.getElementsByTagName().
element.className.
node.nodeValue.
indexOf().
Can't you give the target element an ID? That would make things much more simple. Otherwise, you have to go through all <h3> elements until you find the one you want to hide:
var headings = document.getElementsByTagName("h3");
for(var i=0; i<headings.length; i++) {
var contentElement = headings[i].getElementsByTagName('nobr');
var content = "";
if(contentElement.length) {
content = contentElement[0].textContent ? contentElement[0].textContent : contentElement[0].innerText;
}
var content = contentElement.length ? contentElement[0].childNodes[0].nodeValue : '';
if(headings[i].className == 'ms-standardheader' && content == 'Session') {
headings[i].style.display = 'none';
}
}
you should try this :
window.onload = function()
{
getElementByClass('ms-standardheader');
}
window.getElementByClass = function(theClass){
var allHTMLTags=document.getElementsByTagName('*');
for (i=0; i<allHTMLTags.length; i++) {
if (allHTMLTags[i].className==theClass) {
var content = allHTMLTags[i].innerHTML;
var search = /session/;
if (search.test(content))
{
alert(search);
allHTMLTags[i].style.display='none';
}
}
}
}
See Demo : http://jsfiddle.net/3ETpf/18/
Always favour a unique Id where possible. If not possible then you have to manually traverse the DOM to find the elements you are looking for. Here's an example using getElementsByTagName().
var i, header, headers = document.getElementsByTagName('h3');
for (i = 0; i < headers.length; i += 1) {
header = headers[i];
if (header.className === 'ms-standardheader' &&
(header.textContent || header.innerText) === 'Session') {
header.style.display = 'none';
}
}
see: http://jsfiddle.net/whP5z/
If you have jquery you may type this :
$("h3.ms-standardheader:contains('Session')").hide();
I want to be able to have a javascript function that hides divs for me. For example, I have something like
<div id='container'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
And i would like the function to hide every 'item' class element after say the first 3. How would i go about this?
Thanks for any help
In JS, you could do something like this, provided the item divs are the only children of the container div:
var itemDivs = document.getElementById("container").children;
for(var i = 0; i < itemDivs.length; i++) {
if(i > 2) {
itemDivs[i].style.display = 'none';
}
}
Try it here: http://jsfiddle.net/eY9ZD/
Otherwise, you could do this:
var divs = document.getElementById("container").getElementsByTagName("div");
for(var i = 0; i < itemDivs.length; i++) {
if(i > 2 && divs[i].className == 'item') {
itemDivs[i].style.display = 'none';
}
}
Try it here: http://jsfiddle.net/6TcWE/
And finally, if jQuery is an option, there's a one-liner using the gt selector:
$("#container div.item:gt(2)").hide();
Try it here: http://jsfiddle.net/J8wK6/
With plain JavaScript something like:
function hideElements(elements, start) {
for(var i = 0, length = elements.length; i < length;i++) {
if(i >= start) {
elements[i].style.display = "none";
}
}
}
Then you can do:
var elements = document.getElementById('container').getElementsByClassName('item');
hideElements(elements , 3);
Reference: getElementById, getElementsByClassName
Update:
Interestingly, IE8 seems to support the more powerful querySelectorAll() function. So if you don't care about < IE8, then you can also do:
var elements = document.querySelectorAll('#container .item');
hideElements(elements , 3);
Unfortunately, there is not the "one" solution to select the elements you want in all browsers. If you don't want to think about cross-browser compatibility, consider to use jQuery as #karim suggests.
You can do this easily with jQuery, but your tag doesn't include that so I'm going to show you a vanilla Javascript way:
var divs = document.getElementById('container').getElementsByTagName('div');
var numItemDivs = 0;
for (var i=0; i<divs.length; i++) {
if (divs[i].className == "item") {
numItemDivs++;
if (numItemDivs > 2) {
divs[i].style.display = "none";
}
}
}
If you are just using regular javascript you can do something like this:
var container = document.getElementById("container");
var items = container.childNodes;
for(var i = 0; i < items.length; i++){
if(i >= 3)
items[i].style.display = "none";
}
If you're looking for a pure javascript implementation, this should work; it will also only hide DIV child nodes.
function hideMe(){
var item_list = document.getElementById('container').children;
for(var i = 0; i < item_list.length; i++){
if(i > 2 && item_list[i].tagName == "DIV"){
item_list[i].style.display = "none";
}
}
}
EDIT: changed the style from visibility to display, you probably don't want the layout space lingering.