How to toggle checkbox states - javascript

I can't uncheck a checkbox after I checked it (all via JS/Jquery).
Code:
//Works perfect
function showL(labelObj)
{
var cb = $(labelObj).prev()[0];
$(cb).prop('checked', true);
}
//Does NOT work
function hideL(labelObj)
{
var cb = $(labelObj).next()[0];
//$(cb).attr('checked', false);
$(cb).prop('checked', false);
}
update
It's the same object in both functions:

You can just do.
$('input[type="checkbox"]').on('click', function{
var propState = $(this).prop('checked'); // grab the checkbox checked state.
propState === true ? propState = false : propState = true; // ternary operation. If box is checked uncheck it. if it is not checked check it.
}
It will work on all checkboxes.

Related

D3 using classed() to add and remove class with checkbox

I am having trouble removing a class that I have added using a checkbox. The checkbox is checked to begin with. When it is unchecked by the user it adds a "hideRect" class with classed('hideRect', true);
this works great BUT when I check the box again the class doesn't go away.
Here is my code:
this.$node.append('input')
.attr('type', 'checkbox')
.attr('checked', true)
.attr('value', 'med')
.on('click', () => this.updateRectLine());
}
private updateRectLine() {
//var rect = this.$node.getElementsByClassName('.MEDICATION');
var cbMed = this.$node.attr("checked");
if (cbMed !== true){
this.$node.selectAll(".MEDICATION").classed('hideRect', true);
}
else if (cbMed == true){
this.$node.selectAll(".MEDICATION").classed('hideRect', false);
}
}
thanks in advance!
You need to update the below function like this
private updateRectLine() {
var cbMed = this.$node.select("input[type='checkbox']").prop("checked");
if (!cbMed)
this.$node.selectAll(".MEDICATION").classed('hideRect', true);
else
this.$node.selectAll(".MEDICATION").classed('hideRect', false);
}
.attr() function only returns the value the checkbox was initialized to, to check for a checkbox's check state, you want to use property checked present on check box elements

Local storage not saving the checkbox unchecked stage

I am using jquery and local storage to save the state of a checkbox.
For saving I use:
function save_form() {
window.localStorage.setItem('fb_show', $('#fb_show').val());
alert('Saved');
}
function load_form() {
var fb_checkbox_val = window.localStorage.getItem('fb_show');
alert(fb_checkbox_val);
if (fb_checkbox_val == 'on') {
$("#fb_show").prop("checked", true);
} else {
$("#fb_show").prop("checked", false);
}
}
The problem is that when it's unchecked it will save the value as 'on' so that part worked BUT when I uncheck the checkbox and save it again, it still saves as 'on' ... so the code after that will set it as checked again.
How can I fix this?
You should save the state of the checkbox in localStorage:
function save_form() {
window.localStorage.setItem('fb_show', $('#fb_show').is(':checked'));
alert('Saved');
}
function load_form() {
var fb_checkbox_val = window.localStorage.getItem('fb_show') === 'true' ? true : false;
alert(fb_checkbox_val);
$("#fb_show").prop("checked", fb_checkbox_val);
}
An unchecked checkbox doesn't actually have a value and therefore you have to check whether or not it is checked and save that value. $("#fb_show").is(":checked")

dojo/cbtree uncheck all checkboxes and check selected checkbox

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

filter by checkbox value javascript not working

I'm trying to filter my page by a checkbox value. That way whenever the value exist in a specific row it will filter that row. The problem with my code is the if checked isn't even firing. I know this because the console log message test is not showing up. I don't get any syntax errors in the console but its not seeing that the check box has been checked. I'm a noob at JavaScript. When the checkbox is checked shouldn't the following code fire?
var $row = $("#data tr"),
$filter_poweron = $("#poweron");
if($filter_poweron.checked) {
console.log('test');
var filterText_poweron = $filter_poweron.val().toLowerCase();
$row.each(function () {
var $row_d = $(this);
$row_d.toggle($row_d.text().toLowerCase().indexOf(filterText_poweron) > -1);
});
}
<br><input type="checkbox" id="poweron" value="1O">PoweredOn <input type="checkbox" id='poweroff' value="0F"> PoweredOff
$filter_poweron is a jQuery object. jQuery objects don't have the checked property.
You can get the checked property of the DOM element using .prop():
var $row = $("#data tr"),
$filter_poweron = $("#poweron");
if ($filter_poweron.prop('checked')) {
console.log('test');
var filterText_poweron = $filter_poweron.val().toLowerCase();
$row.each(function () {
var $row_d = $(this);
$row_d.toggle($row_d.text().toLowerCase().indexOf(filterText_poweron) > -1);
});
}
There are other ways to see if a checkbox element is checked:
$filter_poweron[0].checked;
$filter_poweron.is(':checked');
$filter_poweron.filter(':checked').length;
if($(filter_poweron).is(':checked') {
console.log('test');
var filterText_poweron = $filter_poweron.val().toLowerCase();
$row.each(function () {
var $row_d = $(this);
$row_d.toggle($row_d.text().toLowerCase().indexOf(filterText_poweron) > -1);
});
}
use the jquery change event and check if its checked or not
$(filter_poweron).change(function() {
if(this.checked) {
//Do stuff
}
});

Issue with Radio button checked in JavaScript

I am working on a JSP page which is having multiple radio buttons with ids ans1, ans2, ans3... etc.. No of radio buttons varies depending upon on the response in previous page. User should select answer for all the radio buttons. i.e. user must select response for all the radio buttons ans1, ans2, ans3 ... etc. I have written a Javascript code for submit button click event as below for validation and to make sure user has responded to all the answers:
function beforeSubmit(){
var obj = document.quizcreen;
var qCount = obj.totQuesHidden.value;
for (var i=1; i<=qCount; i++){
if(document.getElementById("ans"+i).checked){
// checked
}else{
alert("Please select ateleast one option"); // unchecked
return false;
}
}
obj.submit();
return true;
}
For some reason above code is not working. The form should not be submitted if all the radio buttons are not selected. Please help, I know it's very simple and common issue, but I am unable to figure it out. Thanks in advance.
Also following is the form action:
<form name="quizcreen" id="quizcreen" method="post" action="QuizResult.jsp" onsubmit = "return beforeSubmit();">
You have a return true statement in your loop. So when the first radiobutton is checked, it will not check the other ones.
function beforeSubmit(){
var obj = document.quizcreen;
var qCount = obj.totQuesHidden.value;
var allChecked = true;
for (var i=1; i<=qCount; i++){
if(! document.getElementById("ans"+i).checked){
allChecked = false;
}
}
if(! allChecked){
alert("Please select ateleast one option"); // unchecked
return false
}
obj.submit();
return true;
}
Ok I found out a better way to handle my scenario, So I am sharing my code for your info:
function beforeSubmit() {
var obj = document.quizcreen;
var allChecked = true;
$("input:radio").each(function() {
var name = $(this).attr("name");
if ($("input:radio[name=" + name + "]:checked").length == 0) {
allChecked = false;
}
});
if (!allChecked) {
alert("Please answer all the questions."); // unchecked
return false;
}
obj.submit();
return true;
}
your problem is at least one to be checked.
do this stuff
function isRadioChecked() {
return ($('input[type=radio]:checked').size() > 0);
}

Categories

Resources