I created a checkbox and apply these attributes
let box = document.createElement('input');
box.setAttribute("type","checkbox");
box.setAttribute("id","box");
box.setAttribute("onclick","checkBox(this)");
This is the function
function checkBox(para2){
let condition = box.checked;
if (condition === true) {
para2.parentNode.style.opacity = '0.5'
para2.parentNode.style.textDecoration = "line-through"
}
if (condition === false) {
para2.parentNode.style.opacity = "1";
para2.parentNode.style.textDecoration = "none";
}
}
When I click on first checkbox, style works. But when I click on other children it doesn't work.
In your checkBox function,
let condition = box.checked;
This line specifically checks whether the checkbox "box" is checked. Since you are having multiple checkboxes, I believe you may have box2, box3, etc.
As a solution, you can introduce a "name" attribute to your checkboxes and use a query selector to identify which ones are checked.
let condition = document.querySelectorAll('input[name="color"]');
condition.forEach((cb) => {
if (cb.checked === true) {
// your code
} else {
// your code
}
});
Note: there might be many other possible ways to do this. This is the one that came to my mind right now
Related
So. to begin with,
I am writing my eventlisteners in this way.
document.addEventListener('click',(e)=>{
const element = e.target;
if(element.classList.contains('classOne'){
fire_function_one();
}
if(element.classList.contains('classTwo'){
fire_function_two();
}
});
I have a div like follows
<div class='classOne classTwo'>Something</div>
So what I want to achieve is,
When our div has classOne, I want to fire 'fire_function_one()', However when our div has both classOne and ClassTwo, I want to fire 'fire_function_two()' but I dont want to run 'fire_function_one()'.
What I have tried,
event.stopPropogation; //Not working
event.preventDefault; //Not working
if(element.classList.contains('classTwo' && !element.classList.contains('classOne'){
fire_function_two();
//Doesnt acheive what I want
}
Change the Order of your condition and use else if statement.
document.addEventListener('click',(e)=>{
const element = e.target;
if(element.classList.contains('classTwo'){
fire_function_two();
}
else if(element.classList.contains('classOne'){
fire_function_one();
}
});
If you are sure that the element can have classOne or both classTwo and classOne, you can just change the order and use else if statement:
document.addEventListener('click',(e)=>{
const element = e.target;
if(element.classList.contains('classTwo'){
fire_function_two();
} else if(element.classList.contains('classOne'){
fire_function_one();
}
});
You need to write click on element as below.
var eleOne = document.getElementsByClassName('classOne')
if(eleOne.length > 0) {
var currentEleOne = eleOne[0];
currentEleOne.onclick = function () {
// Click code for classOne
}
}
var eleTwo = document.getElementsByClassName('classTwo')
if(eleTwo.length > 0) {
var currentEleTwo = eleTwo[0];
currentEleTwo.onclick = function () {
// Click code for classTwo
}
}
Here you have two cases,
When both classes are present, fire only class two
If only class one is present, fire class one
So, First check with if whether both classes are present or not. If true then fire class two. Otherwise inside else if, check if class one is present and if this condition is met, fire class one.
document.addEventListener('click', function(e) {
const element = e.target;
if (element.classList.contains('classTwo')) {
console.log("Fire class two");
} else if (element.classList.contains('classOne')) {
console.log("Fire class one");
}
});
<div class='classOne classTwo'>Something 1 2</div>
<div class='classOne'>Something 1</div>
You could try a simple ternary like this:
document.addEventListener('click', (e) => {
const element = e.target;
element.classList.contains('classTwo') ? fire_function_two() : fire_function_one();
});
If the classList contains 'classTwo' then run fire_function_two() else fire_function_one()
$('.checkbox').on('change', function() {
$('.pagination').hide();
$('.callout').hide();
$('.checkbox').each(function() {
if ($(this).prop('checked') === true) {
var checkboxName = $(this).val();
$('.callout').each(function() {
var calloutArray = $(this).data();
var i;
for (i = 0; i < calloutArray.category.length; i++) {
$(this).hide();
if (checkboxName === calloutArray.category[i]) {
$(this).show();
}
}
});
}
});
});
To explain this function it basically listens to see if a checkbox has been clicked and then hides all the callouts on the page.
It then loops through each one of those checkboxes and checks which ones are true on the page. I then create a variable that stores the current checkbox value.
After this I then want to loop through each callout and pull its data from a data attribute.
I then loop through each string in the array and hide the callout no matter what. However if the callout has an array value that is the same as the checkbox value then I need to show it.
This seems to be working without the hide. However I need to hide the callouts if they do not hold the same checked category names which is where I'm running into problems.
The If statement seems to never return true if I have already hidden the callout. So the question is how do I show the callout if the selected checkboxes match one of the callout array strings but hide the callout if the string is not in the callout array.
From what I've understand, the following code is equivalent
$('.checkbox').on('change', function () {
$('.pagination, .callout').hide();
$('.checkbox:checked').each(function () {
var checkboxName = $(this).val();
$('.callout').hide().each(function () {
var calloutArray = $(this).data();
if (calloutArray.category.indexOf(checkboxName) !== -1) {
$(this).show();
}
});
});
});
Merge selectors having common actions(hide())
Use :checked pseudo-selector to select only checked elements
Use hide() on selector and then iterate over it using each()
Use indexOf to check if element is in array
You're showing/hiding your element on each iteration of the loop. That means the result of the last iteration wins, as though you hadn't done the earlier ones at all.
You can just use Array#indexOf to see if the name is in the array, and use the resulting flag to show/hide the callout:
$(this).toggle(calloutArray.category.indexOf(checkboxName) != -1);
E.g.:
$('.checkbox').on('change', function() {
$('.pagination').hide();
$('.callout').hide();
$('.checkbox').each(function() {
if ($(this).prop('checked') === true) {
var checkboxName = $(this).val();
$('.callout').each(function() {
var calloutArray = $(this).data();
$(this).toggle(calloutArray.category.indexOf(checkboxName) != -1);
});
}
});
});
Also note that
if ($(this).prop('checked') === true) {
is quite a long way to write
if (this.checked) {
Similarly, with inputelements, this.value is the same as $(this).val().
I want to make the checkbox work more or less like a radio button in this instance. This is what I have so far. I would like to be able to do this in the treeCheckboxClicked() function so that it would just uncheck all the remaining checkboxs then check the one that was selected.
buildTocTree: function (cp1) {
var self = this;
var toc = new TOC({
checkboxes: false,
enableDelete: true,
deleteRecursive: true,
showRoot: false,
checkBoxes: false,
}, self._viewId + '_tocTree');
toc.on("checkBoxClick", dojo.hitch(this, "treeCheckboxClicked"));
},
treeCheckboxClicked: function (e) {
if (e.checked) {
if (e.subLayers || e.name === 'GISLayer')
this.selectedLayerValue('');
else if (e.layerInfos)
this.selectedLayerValue('');
else
this.selectedLayerValue(e.name);
if (this.selectedLayerValue() != '')
this._selectedGISSourceLayer = e;
else
this._selectedGISSourceLayer = '';
}
}
Without knowing the internal details of the TOC widget, especially its DOM, it's difficult to know how to query all checkboxes within its template. Assuming your treeCheckboxClicked is already getting called, and e.target is the checkbox element itself, the following code should get you close to your desired functionality:
if (e.checked) {
query('checkbox', self.domNode).forEach(function (checkbox) {
checkbox.checked = checkbox != e.target;
});
//...
}
Note: This assumes the dojo/query module has been loaded.
Are you using agsjs.TOC? They have a handler included to do this for you. In the examplesat http://gmaps-utility-gis.googlecode.com/svn/tags/agsjs/latest/examples/toc.html they toggle the function off and on with a button, but you can make it default on and include the following snippet in your tree declaration. (replace DynaLayer 1 with your layer)
toc.on('toc-node-checked', function(evt){
// when check on one layer, turn off everything else on the public safety service.
if (evt.checked && evt.rootLayer && evt.serviceLayer && evt.rootLayer == dynaLayer1){
evt.rootLayer.setVisibleLayers([evt.serviceLayer.id])
}
The following javascript (prototype 1.6) code hides all checkboxes on the page and inserts a div element with some css style and a click event to act as a fake-checkbox. It also looks out for a label next (or previous) the checkbox, to also trigger the same event.
When I click the div (fake_el) itself, everything works as expected, but when I try the same with the label, it only works one time. after that, the el isn't gonna change - as if it (the el) would be a value-parameter.
Any ideas here?
$$('input[type=checkbox]').each(function(el) {
if (el.visible()) {
var fake_el = new Element('div', { className:'checkbox checkbox_' + el.checked });
var label = (el.next() != null && el.next().tagName === 'LABEL' && el.next().readAttribute('for') === el.id) ? el.next() : undefined;
label = (el.previous() != null && el.previous().tagName === 'LABEL' && el.previous().readAttribute('for') === el.id) ? el.previous() : label;
var action = function(el) {
el.checked = (el.checked) ? false : true;
fake_el.className = 'checkbox checkbox_' + el.checked;
}
fake_el.observe('click', function() { action(el); });
if (label != null) { label.observe('click', function() { c.log(el); action(el); c.log(el); }); }
el.insert({ after:fake_el }).hide();
}
});
I changed a couple items and created a jsFiddle for this. First and foremost, c.log had to be changed to console.log for it to work for me :). After that, the only thing I changed was how the divs were added, since it wasn't working for me with insert. I set up some test data and away I went...
EDIT: Perhaps you don't have a non-label tag between two checkboxes and it is getting confused? Notice I have a br between label and the next checkbox, maybe you need to do something like that.
So, I have some faux checkboxes (so I could style them) that work with jQuery to act as checked or not checked. There are a number of faux checkboxes in my document, and for each one I have a click function:
var productInterest = [];
productInterest[0] = false;
productInterest[1] = false;
productInterest[2] = false;
// here is one function of the three:
$('#productOne').click(function() {
if (productInterest[0] == false) {
$(this).addClass("checkboxChecked");
productInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
productInterest[0] = false;
}
});
The problem seems to be that there is an error in the if statement, because it will check, but not uncheck. In other words it will add the class, but the variable won't change so it still thinks its checked. Anybody have any ideas? Thanks for your help.
UPDATE: So, I need to show you all my code because it works in the way I supplied it (thanks commenters for helping me realize that)... just not in the way its actually being used on my site. so below please find the code in its entirety.
Everything needs to happen in one function, because the UI and data for each checkbox need to be updated at once. So here is the complete function:
$('input[name=silkInterest]').click(function() { // they all have the same name
var silkInterest = [];
silkInterest[0] = false;
silkInterest[1] = false;
silkInterest[2] = false;
if ($(this).is('#silkSilk')) { // function stops working because the .is()
if (silkInterest[0] == false) {
$(this).addClass("checkboxChecked");
silkInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[0] = false;
}
alert(silkInterest[0]);
}
if ($(this).is('#silkAlmond')) {
if (silkInterest[1] == false) {
$(this).addClass("checkboxChecked");
silkInterest[1] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[1] = false;
}
}
if ($(this).is('#silkCoconut')) {
if (silkInterest[2] == false) {
$(this).addClass("checkboxChecked");
silkInterest[2] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[2] = false;
}
}
var silkInterestString = silkInterest.toString();
$('input[name=silkInterestAnswer]').val(silkInterestString);
// This last bit puts the code into a hidden field so I can capture it with php.
});
I can't spot the problem in your code, but you can simply use the class you're adding in place of the productInterest array. This lets you condense the code down to a single:
// Condense productOne, productTwo, etc...
$('[id^="product"]').click(function() {
// Condense addClass, removeClass
$(this).toggleClass('checkboxChecked');
});
And to check if one of them is checked:
if ($('#productOne').hasClass('checkboxChecked')) {...}
This'll make sure the UI is always synced to the "data", so if there's other code that's interfering you'll be able to spot it.
Okay, just had a palm to forehead moment. In regards to my revised code- the variables get reset everytime I click. That was the problem. Duh.