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

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");
}
});

Related

Checkbox using Javascript

I have created a table which has a checkbox to select, and pagination is also there for the table. My problem is that if I select two boxes from first page and select few more in the second, only the boxes which i selected in the last page are getting displayed and the others are not coming. Please answer me if u are aware.
Here is my code :
function getSelectedEquipmentIds() {
var equipmentIds = "";
var checkboxs = document.getElementsByName("instance");
for ( var i = 0; i < checkboxs.length; i++) {
if (checkboxs[i].checked) {
equipmentIds += checkboxs[i].value + ";";
}
}
return equipmentIds;
}

HTML. Hide/Show a drop down menu depending on if an option is selected on another drop down menu

I am trying to have originally just one drop down menu when a website loads. Lets say that drop down menu only has two options "A" and "B". If the user selects option "A" I want another drop menu then to appear on the website (just below the original). If the user selects option "B" I want a different menu to appear below the original. I am also using PHP to make things even more complicated. Can anyone guide me on how I can accomplish this?
Modify the two dropdowns with attribute style="display:none". In your javascript function you would have an event registered that based on the SelectedIndex you would choose which dropdown element to remove the style="display:none" from.
This should do the work :
$("#drop").change(function() {
if( $('#drop option:selected').val() == "A") {
//Do what you want
}
else if ( $('#drop option:selected').val() == "B") {
//Do what you want
}
});
I don't know your level in js, if you need more explanations, please let me know.
Here's an example of manipulating the classes using native JavaScript. It could be cleaner, but it shows how you can check agains what classes exist in order to set CSS behaviour.
var cont = document.body.appendChild(document.createElement('div'));
cont.className = 'row';
for (var i = 0; i < 3; i++ ) {
var menuitem = cont.appendChild(document.createElement('div'));
menuitem.className = 'col';
var internal = menuitem.appendChild(document.createElement('div'));
internal.appendChild(document.createTextNode('item'+ (i + 1)));
(internal.attachEvent) ?
internal.attachEvent('onclick', function () {
for (var j = 0; j < cont.children.length; j++){
if (cont.children[j].className === 'col active') {
cont.children[j].className = 'col';
}
};
this.parentElement.className = 'col active';
}) :
internal.addEventListener('click', function () {
for (var j = 0; j < cont.children.length; j++){
if (cont.children[j].className === 'col active') {
cont.children[j].className = 'col';
}
};
this.parentElement.className = 'col active';
}, false);
};

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.

How do you count checked checkboxes, excluding the header, in an asp.net gridview using javascript?

I'm currently counting all the checked checkboxes in an asp.net gridview using:
$('#cphMain_gdvSalesOrder').delegate('input:checkbox', 'click', function() {
var count = $('#cphMain_gdvSalesOrder').find('input:checkbox:checked').length;
Whereas I need to count all the checkboxes that are checked apart from the one in the header.
Any ideas would be great, thanks
Korv
You can assign a "flag" CSS Class to the check-boxes in the grid which is not assigned to the check-box in the header. This way you can filter out the header check-box as part of your selector based on CSS Class.
:not(.headerCheckBox)
var count = 0;
var grid = document.getElementById("<%=grdProductImage.ClientID%>");
var chk = grid.getElementsByTagName("input");
for (var i = 0; i < chk.length; i++)
{
if (chk[i].checked && chk[i].id.indexOf("chkAll") == -1) {
count = count + 1;
}
}

disable all the elements in html

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.

Categories

Resources