disable all the elements in html - javascript

How can we disable all the elements in html through javascript.The easiest way...

I suggest to do it the "Lightbox"-style way.
Add an absolute positioned, transparent, full screen div Layer above the Page.
This way, the user can't even click on a Link.
To give the user a visual feedback that the page is disabled,
you can make the div e. g. 50% transparent black.
BTW, here is also a jQuery Plugin that uses a similar technique.

The easiest way is to put all form elements you want to disable inside a <fieldset> and then disable the fieldset itself.
An example: http://jsfiddle.net/xdkf9b8j/1/
If you don't want the border around the fieldset, remove it per css.

Try this,
function disableForm(theform) {
if (document.all || document.getElementById) {
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (true) {
formElement.disabled = true;
}
}
}
}
Or else you can try this too, as RaYell said
function disableForm() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
selects[i].disabled = true;
}
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
textareas[i].disabled = true;
}
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
To disable the whole page you can find some info here,

I don't know why you would need that but this will work:
// this will disable all input elements
var elems = document.getElementsByTagName('input');
var len = elems.length;
for (var i = 0; i < len; i++) {
elems[i].disabled = true;
}

All the form elements (inputs, selects, textareas) within a form, are accesible through the form.elements HTMLCollection, you can iterate the collection disabling each element:
function disableForm(form) {
var length = form.elements.length,
i;
for (i=0; i < length; i++) {
form.elements[i].disabled = true;
}
}
Usage examples:
disableForm(document.forms[0]);
disableForm(document.getElementById('formId'));

Once i had to create a tutorial for my website. I needed to disable all interactions on a page excluding some elements. To do so i used this method:
First make sure to remove all events bindings from your page elements. You can do this by using:
$('*').unbind();
Next disable all links on your page:
$('a').each(function(){$(this).click(function(){return false;})});
and disable all inputs:
$('input').attr('disabled', true);
The code needs to be executed at the end of your document. BTW you may exclude some elements within jquery selector to keep them active.

To lock:
var controls = document.querySelectorAll("button, input, select, textarea");
for (var c of controls) {
c.disabled = true;
}
To unlock:
var controls = document.querySelectorAll("button, input, select, textarea");
for (var c of controls) {
c.disabled = false;
}
That simple.

Just and without crutches!
/**
* Enable/disable all form controlls
* #param status Status: true - form active, false - form unactive
*/
HTMLFormElement.prototype.setStatus = function (status) {
for (var i in this.elements) {
this.elements[i].disabled = !status;
}
};
// Example:
var my_form = document.getElementById('my_form_with_many_inputs');
my_form.setStatus(false); // Disable all inputs in form
my_form.setStatus(true); // Enable all inputs in form

Depending what result you need you could also do
`document.getElementById('main_form').style.display = 'none';`
Where main_form is the id of your form. You can use the same technique to hide a div containing whatever elements you want to disable.

The best way is to add a div with highest z-index having width:100% and height:100%.It will cover your entire page and make everything not clickable means disabled virtually.It is best,because it will not use any loop and any complex code.

Related

Add Different Data Attribute to Anchors

I'm attempting to add data-webpart attributes to all the anchors within a document, but populate their values with the data attributes of their containing divs.
However the code I wrote appears to be populating all of the anchors with only one of the data attributes (or rather, adding the first one to all, then adding the second).
Any help would be much appreciated!
HTML
<body>
<div data-webpart="form">
Test Link
Test Link
Test Link
</div>
<div data-webpart="icon-grid">
Test Link
Test Link
Test Link
</div>
</body>
JavaScript
// data attributer
var webParts = document.querySelectorAll("[data-webpart]");
var webPartAnchors = document.querySelectorAll("[data-webpart] > a");
function addDataAttr() {
var closestWebPartAttr;
for (i = 0; i < webPartAnchors.length; i++) {
for (e = 0; e < webParts.length; e++) {
closestWebPartAttr = webParts[e].getAttribute("data-webpart");
webPartAnchors[i].setAttribute("data-web-part", closestWebPartAttr);
}
}
}
window.onload = function() {
if (webParts !== null) { addDataAttr(); }
};
Your nested loops are copying the data attribute from every DIV to every anchor, because there's nothing that relates each anchor to just their parent. At the end they all have the last data attribute.
Since the anchors are direct children of the DIV, you don't need to use querySelectorAll() to get them, you can just use .children() within the loop.
function addDataAttr() {
for (var i = 0; i < webParts.length; i++) {
var webpart = webParts[i].dataset.webpart;
var children = webParts[i].children;
for (var j = 0; j < children.length; j++) {
children[j].dataset.webpart = webpart;
}
}
}

Javascript - Toggle Multiple Classes onclick

I am trying to toggle multiple classes onclick using vanilla Javascript. What i am trying to do is when a btn is clicked two classes to toggle with another two classes. I have 5 classes in total which are: .menu_btn , .main_nav, .btn_active, .container, .container_active. When i press the .menu_btn i would like the classes .main_nav to toggle with .btn_active and at the same time i would like to have the .container to toggle with .container_active. The class .container is the only one that has 5 elements of that class, the others are single. I have done this using jQuery but i would like to know the way using vanilla Javascript. Hopefully someone can help.
One thing to point out is when i console.log the .btn_active and .container_active i get back [ ] an empty array. Those 2 css classes are not assigned to any element of my project. They are existing only in the css and their purpose is for toggle.
Thanks
jQuery Code:
$(function(){
$(".menu_btn").on("click", function(){
$(".main_nav").toggleClass("btn_active");
$(".container").toggleClass("container_active");
});
});
Vanilla Javascript Code:
var menuBtn = document.getElementsByClassName("menu_btn");
var mainNav = document.getElementsByClassName("main_nav");
var btnActive = document.getElementsByClassName("btn_active");
var container = document.getElementsByClassName("container");
var containerActive = document.getElementsByClassName("container_active");
menuBtn.onclick = function(){
mainNav.classList.toggle(btnActive);
for ( index = 0; index <= container.lenght -1; index++ ){
container[index].classList.toggle(containerActive);
}
};
I have modified your script and created a fiddle so you see how it works: https://jsfiddle.net/eyrpdsc2/
The toggle accepts a string as a parameter, not a Node. So you need to pass 'btn_active' instead of btnActive. Also keep in mind that querySelectorAll returns a NodeList (not an array) so you cannot use forEach.
var menuBtn = document.querySelectorAll(".menu_btn");
var mainNav = document.querySelectorAll(".main_nav");
var container = document.querySelectorAll(".container");
for (var i = 0; i < menuBtn.length; ++i) {
menuBtn[i].addEventListener('click', toggleClasses);
}
function toggleClasses() {
var i = 0;
for (i = 0; i < mainNav.length; ++i) {
mainNav[i].classList.toggle('btn_active');
}
for (i = 0; i < container.length; ++i) {
container[i].classList.toggle('container_active');
}
}

Check appropriate checkboxes when certain option is selected from dropdown select?

fiddle
I'm sorry to ask this question, I hate asking on here and I don't wanna be seen as a vampire but I'm so stuck with this and I don't think I'm on the right lines at all, if this doesn't make sense at all comment and I'll try explain. I'm desperate!
Basically what I'm working on requires you to select a company, and when you do that it generates some checkboxes. When you select a profile from the dropdown, it needs to tick the appropriate checkboxes. The checkboxes it should tick are whatever that profile has in it's PRIVILEGE_PROFILES.PRIVILEGE CODES (these are the checkboxes).
I've got my code in a fiddle here http://jsfiddle.net/shaunyweasel/dj8jr19e/5/ . The arrays are at the top of the fiddle. I was trying to do it so that if the text value of the label was equivalent to to the SEC_PRIVILEGES.Name then tick those checkboxes, however that doesn't really work so I'm not sure if there's a better way to go about it. The below method is what I've been working on to try get it to tick the checkboxes but I'm pretty sure it's wrong.
$(document).on('change', '#select_profile', function () {
var select = $("#select_profile option:selected").text(),
selectedProfile, privileges, div, label, access;
var checked = document.getElementsByTagName('input');
for (var i = 0; i < checked.length; i++) {
if (checked[i].type == 'checkbox') {
checked[i].checked = false;
}
}
if (select !== 'None') {
for (var i = 0; i < PRIVILEGE_PROFILES.length; i++) {
if (PRIVILEGE_PROFILES[i].PROFILE_ID === select) {
selectedProfile = PRIVILEGE_PROFILES[i];
privileges = selectedProfile.PRIVILEGE_CODE;
}
}
for (var i = 0; i < SEC_Privileges.length; i++) {
if (privileges[i] === SEC_Privileges[i].Unique_Code) {
console.log(privileges);
var labels = document.getElementsByTagName('label');
var checked = document.getElementsByTagName('input');
for (var c = 0; c < checked.length; c++) {
if (SEC_Privileges[i].Name == labels) {
checked[c].checked = true;
}
}
}
}
}
});
If this doesn't make sense, here's a step by step of how it works and where i'm at and stuck:
User selects a company from the company_selection dropdown
When company is selected it generates checkboxes for that company depending on it's COMPANY_PRIVILEGES.UNIQUE_CODE (the array)
The user then has to select something from the profile_selection, and depending what profile they select it will check the appropriate checkboxes, depending on what PRIVILEGE_PROFILES.PRIVILEGE_CODES it has. (so if you selected Crew then it would just tick the View Tyrell box as that's the only profile it has)
Is there a reason why you do not use jQuery selectors in your code?
Anyway, I've made an update to solve your problem (not using jQuery) http://jsfiddle.net/dj8jr19e/7/
The main issue is that you did not set any IDs to your checkboxes.
I've set an ID corresponding to the Unique_Code of your privileges.
access.id = SEC_Privileges[i].Unique_Code;
Then when you iterate through the associated privileges from the selected profile, I've simply used getElementById because the privileges contains Unique_Code used as Ids of the checkboxes.
Here is the working example: DEMO
I have changed following things:
1) When you are creating the checkboxes then i have added class name to those checkboxes similar to UNIQUE_CODE
$(document).on('change', '#select_company', function () {
// declare variables before the function
var select = $("#select_company option:selected").text(),
selectedProfile, privileges, div, label, access;
// remove access checkboxes from previously selected profile
$('.apps input[type=checkbox]').remove();
$('.apps label').remove();
// if the selected option is 'None', do nothing, else...
if (select !== 'None') {
// match the selected profile in the dropdown with the JS PROFILES object
for (var i = 0; i < COMPANY_PRIVILEGES.length; i++) {
if (COMPANY_PRIVILEGES[i].COMPANY_CODE === select) {
selectedProfile = COMPANY_PRIVILEGES[i];
privileges = selectedProfile.UNIQUE_CODE;
}
}
// match the associated privileges from the profile within the entire privilege list
for (var j = 0; j < privileges.length; j++) {
for (var i = 0; i < SEC_Privileges.length; i++) {
if (privileges[j] === SEC_Privileges[i].Unique_Code) {
// get the div with the id === SEC_Privileges[i].Group_code
div = document.getElementById(SEC_Privileges[i].Group_Code);
access = document.createElement('input');
access.type = 'checkbox';
access.className = SEC_Privileges[i].Unique_Code;
label = document.createElement('label');
// create a textnode with the unique code from the privileges
label.appendChild(document.createTextNode(SEC_Privileges[i].Name));
div.appendChild(label);
div.appendChild(access);
}
}
}
}
});
2) Written simple function to check the checkbox based on the classname:
$(document).on('change', '#select_profile', function () {
var selectedValue = $("#select_profile option:selected").text(),
selectedProfile, privileges, div, label, access;
console.log(selectedValue);
for (var i = 0; i < PRIVILEGE_PROFILES.length; i++) {
if (PRIVILEGE_PROFILES[i].PROFILE_ID === selectedValue) {
privileges = PRIVILEGE_PROFILES[i].PRIVILEGE_CODE;
}
}
for(var j = 0; j < privileges.length; j++) {
$('.'+privileges[j]).attr("checked", "true");
}
});

How do I filter an unorderded list to display only selected items using Javascript?

I have this JSFiddle where I am trying to make it so that the items in an unordered list are visible only if the option selected in a drop down matches their class. List items may have multiple classes, but so long as at least one class matches, the item should be made visible.
The Javascript looks like this:
function showListCategories() {
var selection = document.getElementById("listDisplayer").selectedIndex;
var unHidden = document.getElementsByClassName(selection);
for (var i = 0; i < unHidden.length; i++) {
unHidden[i].style.display = 'visible';
}
};
The idea is that it gets the current selection from the drop down, creates an array based on the matching classes, then cycles through each item and sets the CSS to be hidden on each one.
However, it's not working. Can anyone tell me where I'm going wroing?
Note that I haven't yet coded the "show all" option. I think I'll probably be able to figure that out once I have this first problem solved.
In your fiddle change load script No wrap - in <head>.
Just change your function like following
function showListCategories() {
var lis = document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
lis[i].style.display = 'none';
}
//above code to reset all lis if they are already shown
var selection = document.getElementById("listDisplayer").value;
lis = document.getElementsByClassName(selection);
for (var i = 0; i < lis.length; i++) {
lis[i].style.display = 'block';
}
};
and in css it should be none not hidden
.cats, .rats, .bats {
display: none;
}
If you want to show all li when showAll is selected, add all classes to all lis.
You have a few things going on. First, your fiddle is not setup correctly, if you open the console you'll see:
Uncaught ReferenceError: showListCategories is not defined
This means that the function doesn't exist at the point you attach the event or that the function is out of scope, because by default jsFiddle will wrap your code in the onLoad event. To fix it you need to load the script as No wrap - in <body>.
Second, there's no such thing as a display:visible property in CSS. The property you want to toggle is display:none and display:list-item, as this is the default style of <li> elements.
Now, to make this work, it is easier if you add a common class to all items, let's say item, that way you can hide them all, and just show the one you want by checking if it has a certain class, as opposed to querying the DOM many times. You should cache your selectors, it is not necessary to query every time you call the function:
var select = document.getElementById('listDisplayer');
var items = document.getElementsByClassName('item');
function showListCategories() {
var selection = select.options[select.selectedIndex].value;
for (var i=0; i<items.length; i++) {
if (items[i].className.indexOf(selection) > -1) {
items[i].style.display = 'list-item';
} else {
items[i].style.display = 'none';
}
}
}
Demo: http://jsfiddle.net/E2DKh/28/
First there is no property in Css like display:hidden; it should be display: none;
here is the solution please not that i am doing it by targeting id finished
Js function
var selection = document.getElementById("listDisplayer");
var list = document.getElementsByTagName('li');
selection.onchange = function () {
var value = selection.options[selection.selectedIndex].value; // to get Value
for (var i = 0; i < list.length; i++) {
if (list[i].className.indexOf(value) > -1) {
list[i].style.display = "list-item";
} else {
list[i].style.display = "none"
}
}
}
css Code
.cats, .rats, .bats {
display: none;
}
JSFIDDLE
You have many things wrong in your code and a wrong setting in the jsFiddle. Here's a working version that also implements the "all" option:
Working demo: http://jsfiddle.net/jfriend00/5Efc5/
function applyToList(list, fn) {
for (var i = 0; i < list.length; i++) {
fn(list[i], list);
}
}
function hide(list) {
applyToList(list, function(item) {
item.style.display = "none";
});
}
function show(list) {
applyToList(list, function(item) {
item.style.display = "block";
});
}
function showListCategories() {
var value = document.getElementById("listDisplayer").value;
var itemList = document.getElementById("itemList");
var items = itemList.getElementsByTagName("li");
if (value === "all") {
show(items);
} else {
// hide all items by default
hide(items);
show(itemList.getElementsByClassName(value));
}
}
Changes made:
You have to fetch the .value of the select to see what the value was of the option that was picked. You were using the selectedIndex which is just a number.
A common technique for displaying only a set of objects is to hide all of them, then show just the ones you want. Since the browser only does one repaint for the entire operation, this is still visually seamless.
When finding items that match your class, you should be searching only the <ul>, not the entire document. I added an id to that <ul> tag so it can be found and then searched.
To save code, I added some utility functions for operating on an HTMLCollection or nodeList.
Tests for the "all" option and shows them all if that is selected
Changed the jsFiddle to the Head option so the code is available in the global scope so the HTML can find your change handler function.
Switched style settings to "block" and "none" since "visible" is not a valid setting for style.display.

When function is applied, all select boxes take 2 clicks to open drop down menu?

Prior to adding this code to my page, if, when executed, I notice that all of my select boxes take 2 clicks of the user to open the drop down menu, the first click seems like it sets focus on it, then the 2nd click finally opens it. If I remove the code, the behaviour changes, and the user is able to open the drop down with all of its menu options in only 1 single click.
I am not sure what to fix or modify, so that it doesn't take 2 clicks, im also using ie. 7 so this would be a work around of css focus. I do not wish to have any jquery please.
Thanks for all your help.
function v9_form() {
//===========================================================================================>>
var x = document.getElementsByTagName('INPUT');
for (var i = 0; i < x.length; i++) {
if (x[i].type == "text" && x[i].readOnly == false) {
if (x[i].id != "date2" && x[i].id != "date3") {
x[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4';};
x[i].onblur = function() { this.style.backgroundColor = '#FFFFFF';};
}
}//end of if
}//end of for
var y = document.getElementsByTagName('SELECT');
for (var i = 0; i < y.length; i++) {
y[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4'; };
y[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; };
}
var z = document.getElementsByTagName('TEXTAREA');
for (var i = 0; i < z.length; i++) {
z[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4'; };
z[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; };
}
}
This is a known issue with IE. If you change any of the style in the onfocus IE doesn't display the dropdown choices.
A solution is to use the onfocusin event for IE:
y[i].onfocusin = function() { this.style.backgroundColor = '#FFFFC4'; }
From MSDN:
Fires for an element just prior to setting focus on that element.
Another option is to use the :focus CSS selector but you're obviously limited to CSS with that, no complex Javascript logic.
You're a victim of this bug.
It looks like this is some special behavior from IE. There's some code in that answer that provides a possible workaround you can try, but it's pretty heavy for what it does (accommodate people with old versions of IE). I think your best option would be to use a CSS pseudo class (as recommended by the answer above), or to just remove the functionality for those using IE<8.

Categories

Resources