dojo/cbtree uncheck all checkboxes and check selected checkbox - javascript

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])
}

Related

Is there anything that I am missing?

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

Javascript contenteditable on innerhtml created object

I have this code that is supposed to create a new list item (li) that is editable (contenteditable="true"):
var currenthtml = document.getElementById("0").innerHTML;
var newhtml = currenthtml + '<li class="object" contenteditable="true">...</li>';
The object is created and visible, the purehtml for #0 after editing is:
<div id="0">
<li class="object" contenteditable="true">First object</li>
</div>
To save the content, I have the following helper:
function SaveObject(html) {
localStorage.setItem("obj", html);
}
which is supposed to be called because of:
$('li[contenteditable]').keydown(function(e) {
if (e.keyCode === 13) {
document.execCommand('insertHTML', false, '');
$(this).blur();
var html = document.getElementById("0").innerHTML;
SaveObject(html);
return false;
}
});
(I'll change it to save on other cases, but this is the current saving method.)
but when I edit a new item and try to save, it is not saved the text. It stays there temporarily, but then changes to the default "...". How can I make this work?
The #0 is set this way
if(localStorage.getItem("obj") != null) {
document.getElementById("0").innerHTML = localStorage.getItem("obj");
}
Well, there's several steps you should check:
in your keydown handler, check the value of html:
$('li[contenteditable]').keydown(function(e) {
if (e.keyCode === 13) {
document.execCommand('insertHTML', false, '');
$(this).blur();
var html = document.getElementById("0").innerHTML;
console.log(html); // is the value equal to what is expected?
SaveObject(html);
return false;
}
});
Second, try to check if it is saved to local storage directly after you have saved:
$('li[contenteditable]').keydown(function(e) {
if (e.keyCode === 13) {
document.execCommand('insertHTML', false, '');
$(this).blur();
var html = document.getElementById("0").innerHTML;
SaveObject(html);
console.log(localStorage.getItem("obj")); // is the value equal to what was saved?
return false;
}
});
If the two answers are "yes", check out the value after reloading of your page: just type localStorage.getItem("obj") in your console.
Finally, if the data is still there, make sure that you actually add it back to DOM. You haven't shown us the code which adds list items with the saved data to the page.

Jquery - Identify if radio button value has not changed

Is it possible to identify if the value of radio button has not changed?
Currently I am trying to change the confirmation message of submit button on button changed, and do not want any message if the value has not changed. I have something like this now:
$('input[type="radio"]').change(function() {
var selected = $('input:checked[type="radio"]').val();
if(selected == 'true') {
$("#submit_button").data("confirm", "foo");
} else if(selected == 'false') {
$('#fee').hide();
$("#submit_button").data("confirm", "bar");
}
This will change confirm message to foo if button selected is true, and bar if button selected is false. However, what if I want to return nothing (no message), if radio button by default is true, and selected is true?
You can start a variable outside the event:
var radioChanged = 0;
And, in your event increase it:
$(':radio').change(function() {
radioChanged += 1;
// your code ...
});
Then, later on:
if (radioChanged > 0) {
alert('Change function occurred ' + radioChanged + ' times.');
} else {
alert('Radio button not changed.');
}
As i understand your expected behaviour, check if any radio has no more its default checked value:
$('form').on('submit', function() {
var anyRadioChanged = !!$(this).find('input[type="radio"]').filter(function() {
return $(this).is(':checked') != this.defaultChecked;
}).length; // '!!' to get boolean but it doesn't really matter here
if(anyRadioChanged) {
// show message(???)
}
})
you can hide message element just adding display: none to it or use jquery hide method
$('#someElementId').hide();
or
$('#someElementId').css("display","none")

If select input equals value do this, if it is changed remove those changes

I have a select box called "requestHistoryRequestType". I'm trying to write some jQuery so that when the value of that select box is changed I call a function that adds a class and attribute to a field and appends a span to the field that I pass in as a parameter.
The problem is if a user chooses EXPAPP or EXPDEN but then changes their selection to NA it should remove the added stuff from the previous fields and add the same stuff to a different field. Kinda hard to explain, but ask questions away! I'm kinda new to writing complex jQuery like this.
The function that does the adding classes and such:
function requiredField(requiredField) {
$(requiredField).parent().addClass('has-error');
$(requiredField).attr('data-rule-required', true);
$("label[for='" + requiredField.replace('#', '') + "']").append("<span style='color:#b94a48;' class='has-error has-tooltip' data-placement='right' title='Required Field'>*</span>");
}
The actual on change listener:
//Validations for EXPAPP, EXPDEN, and NA
$("#requestHistoryRequestType").on("change", function() {
if ($("#requestHistoryRequestType").val() === "EXPAPP" || $("#requestHistoryRequestType").val() === "EXPDEN"){
requiredField("#requestHistoryVerbalDateTime");
requiredField("#requestHistoryWrittenDateTime");
} else if ($("#requestHistoryRequestType").val() === "NA") {
requiredField("#requestHistoryComments");
}
});
Thanks Stack!
Create a function that would remove the added stuff from all fields and call it before requiredField() calls:
function removeRequiredFields()
{
var $fields = $("#requestHistoryVerbalDateTime, #requestHistoryWrittenDateTime, #requestHistoryComments");
$fields.parent().removeClass('has-error');
$fields.attr('data-rule-required', false);
$fields.each(function() {
$("label[for='"+$(this).attr('id')+"']").find("[title='Required Field']").remove();
});
}
Or you can pass $fields from the event handler to removeRequiredFields() instead of hardcoding it there, for added flexibility.
I would just have a separate function for when you select a "NA" rather then trying to build that functionality into the same function.
I'll rewrite your event handler to make it a bit cleaner as well (IMO).
//Validations for EXPAPP, EXPDEN, and NA
$("#requestHistoryRequestType").on("change", function() {
var selectedVal = $(this).val();
if (selectedVal === "EXPAPP" || selectedVal === "EXPDEN"){
requiredField("#requestHistoryVerbalDateTime");
requiredField("#requestHistoryWrittenDateTime");
} else if (selectedVal === "NA") {
requiredField("#requestHistoryComments");
}
});
This way you are not hitting the DOM a potential 3 time to test your conditions every time an event is triggered. A minor change but probably a useful one as you get into more complex and larger jQuery selectors.
Edit: If you feel you MUST do it in one function then you can call the function with both elements you want to append
function requiredField(requiredField1, requiredField2) {
if (requiredField2 != null){
$(requiredField1,requiredField1).parent().addClass('has-error');
$(requiredField1,requiredField1).attr('data-rule-required', true);
var requiredLabel = "<span style='color:#b94a48;' class='has-error has-tooltip' data-placement='right' title='Required Field'>*</span>"
$("label[for='" + requiredField1.replace('#', '') + "']").append(requiredLabel);
$("label[for='" + requiredField2.replace('#', '') + "']").append(requiredLabel);
}
else {
//remove multiple element classes and add it to the single one representing the "NA"
}
}
This is based on you only ever having one case where you would be passing a single "requiredField" on a case of a "NA"

js code to replace checkbox and closures

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.

Categories

Resources