use Dojo to detect if all checkboxes are unchecked, disable a button - javascript

I have a group of checkboxes and a QUERY button so user can check a few things and click QUERY button to make a service call to return records. How to disable the QUERY button if none of the checkboxes are checked?
Below are the codes I wrote. The QUERY button got disabled when I first time unchecked all of them. But when I checked only one of checkboxes back again, the array "unchecked" became empty. please help!
_bindChkChangeEvent: function(){
var unchecked = [];
on(query('.chk'), 'change', lang.hitch(this, function(event) {
if(!event.target.checked){
if(unchecked.indexOf(event.target.id) < 0)
unchecked.push(event.target.id);
}
else{
if(unchecked.indexOf(event.target.id) > -1)
unchecked.splice(event.target.id);
}
this._switchQueryBtn(unchecked);
}));
},
_switchQueryBtn: function(unchecked){
if(unchecked.length == 10)
html.addClass(this.btnQuery, 'disabled');
else
html.removeClass(this.btnQuery, 'disabled');
},

At the following link a working example, you can try to adopt this concept to your code (unfortunately the question contains only a partial code view).
https://jsfiddle.net/zmh7bbrf/
What the script does:
Create two checkboxes programmatically.
Create a button programmatically.
Add event handler onChange for each checkbox.
Function showHideButton actually contains the logic to show or hide the button.
Now when the page load, both checkboxes are unchecked, showHideButton runs and button is being disabled.
When User click on a checkbox, re-run function showHideButton.
At this point condition is not met, as one checkbox is checked now, so re-enable the button.
The script could work with any number of checkboxes, just add their reference and modify the logic in showHideButton function.
Notes:
You can use dijit/registry to find references of your widgets, instead of using dojo/query and querying the DOM directly as in the code in your original question.
More information on dijit/registry can be found here:
https://dojotoolkit.org/reference-guide/1.10/dijit/registry.html
require(["dijit/form/CheckBox", "dijit/registry", "dijit/form/Button", "dojo/domReady!"], function(CheckBox, registry, Button) {
new CheckBox({
id: "checkBox0",
name: "checkBox0",
value: "option0",
checked: false,
onChange: function(event) {
showHideButton();
}
}, "checkBox0").startup();
new CheckBox({
id: "checkBox1",
name: "checkBox1",
value: "option1",
checked: false,
onChange: function(event) {
showHideButton();
}
}, "checkBox1").startup();
new Button({
label: "Click me!",
onClick: function() {;
}
}, "button").startup();
var showHideButton = function() {
var checkBox0 = registry.byId('checkBox0'),
checkBox1 = registry.byId('checkBox1'),
button = registry.byId('button');
if (!checkBox0.checked && !checkBox1.checked) {
button.set('disabled', true);
} else {
button.set('disabled', false);
}
};
showHideButton();
});
<input id="checkBox0" />
<label for="checkBox">Option 0</label>
<br>
<input id="checkBox1" />
<label for="checkBox">Option 1</label>
<br>
<button id="button" type="button"></button>

Related

HTML Form Radio Buttons and Checkboxes

I want to create a form in which if a radio button is selected, some checkboxes associated with it open up and the user must select at least one of the checkboxes under that radio button before submitting the form. For example refer to the codepen : https://codepen.io/anon/pen/zJKPRK. This is based on a dogs/cats tutorial I saw.
Here, item propagation is used to make all child items required:
var FormStuff = {
init: function() {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function() {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function() {
$(".require-if-active").each(function() {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
} else {
el.prop("required", false);
}
});
},
};
FormStuff.init();
Here at least 1 radio button needs to be selected and if ClassB or ClassC is selected, I want that the user should select at least one checkbox under that particular class. Any suggestions?
.length gives you the count of elements in your selection. $('input[type="checkbox"]').is(':checked').length > 0 tells you whether or not at least 1 Checkbox has been checked. Just add classes to your selector as desired.

Jqgrid - Validation on selecting dropdown

i have this column with dropdown, currently when i select any value from the dropdown it it gets saved, i would like to add a validation while selecting a value from dropdown before saving, for example,
{name:'color_name',
cellattr: function (rowid, cellValue) {
if ($.inArray(cellValue, hilightcolorcell) < 0) {
return " class='redcells'";
}
},editable:true,edittype:"select",editoptions:
{value:"PURPLE:PURPLE;PINK:PINK;GREEN:GREEN"}}
if the selected value was PINK, i wanted to have a validation prompt with Save and Cancel button something like this, Selected Value is : PINK, SAVE CANCEL
this is demo link https://jsfiddle.net/kwu7v3fc/3/
please help.
There are many ways to implement your requirement. The most native would seems to me to ask the confirmation from the user directly on change of the select option and before real saving it. One can add "change" event handler, which do all you need. The corresponding implementation will look like on the example below
editoptions: {
value: "PURPLE:PURPLE;PINK:PINK;GREEN:GREEN",
dataEvents: [
{
type: "change",
fn: function (e) {
if ($(this).val() === "PINK") {
if (!confirm("Are you sure you want PINK?")) {
// reset the value to the previous one
var savedRow = $("#rowed5").jqGrid("getGridParam", "savedRow");
$(this).val(savedRow[0].v);
}
}
}
}
]
}
See the modified demo https://jsfiddle.net/OlegKi/kwu7v3fc/5/

Knockout: How to pass the Checkbox "checked" value to a Click handler function?

I want to send "true/false" value to a click handler, depending if the checkbox is checked or not.
On check, it should send a 3rd parameter (isChecked) with value "true".
On uncheck, it should send a 3rd parameter (isChecked) with value "false".
I'm sure this is really easy, but I'm having a hard time figuring it out.
Here is the input element:
<input class="cards-view--item-checkbox pull-right" type="checkbox"
data-bind="value: universalParcelId, checked: $parent.isChecked, checkedValue: true,
click: function(data, event, isChecked) {
return $root.addUPIDtoArray(data, event, $parent.isChecked()) }">
Click handler:
addUPIDtoArray: function (data, event, isChecked) {
var self = this;
self.isChecked = ko.observable();
// If checked
if(isChecked()) {
self.upIDArray.push(data.universalParcelId);
self.upIDWithIndexArray.push({
universalParcelID: data.universalParcelId,
searchResultIndex: data.searchResultIndex
});
// If unchecked
} else if(!isChecked()) {
// remove from array
}
return true; // allow the default "click" action, which is checking the box with a "check"
},
I thought i could use the "event" parameter, but for some reason it is coming through as a jQuery.event, instead of a regular DOM event. So I decided for the 3rd parameter. But it just doesn't work like this: gives error $parent.isChecked is not a function
Any ideas?
I got it to work by utilizing $element.checked and passing that as a parameter to my click handler function
<input style="display: none;" class="cards-view--item-checkbox pull-right" type="checkbox"
data-bind="value: universalParcelId, checked: $parent.isChecked, click: function(data, event) {
return $root.addUPIDtoArray($element.checked, data, event) }">
It might not be "best practice" but it works! What objections are there to doing it this way?
Unless you need to distinguish a click from some other way of setting the variable in the checked binding, you don't want a click handler. You just want to subscribe to the variable, which will execute your function whenever its value changes.
You've written your click binding as if adding the parameter to the parameter list will make Knockout know what to pass it. You'll want to re-think that. Generally, it's best to write your click handler as a member of your ViewModel and just make the binding like click: methodName.
Below is an example of a click binding on a checkbox. There's an interval toggling the checkbox each second. That won't trigger the click binding.
There is also a subscription that counts the times the value has changed, and what the last value was.
vm = {
box: ko.observable(true),
changes: ko.observable(0),
lastChange: ko.observable(''),
stuff: ko.observableArray(),
doThing: function() {
vm.stuff.push(vm.box() ? 'checked' : 'not');
return true;
}
};
vm.box.subscribe(function(newValue) {
vm.changes(vm.changes() + 1);
vm.lastChange(newValue ? 'checked' : 'not');
});
ko.applyBindings(vm);
// This will change the checkbox without firing the click
setInterval(function() {
vm.box(!vm.box());
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="checkbox" data-bind="checked: box, click: doThing" />
<div>Changes: <span data-bind="text:changes"></span>, last:<span data-bind="text:lastChange"></span>
<div data-bind="foreach:stuff">
<div data-bind="text: $data"></div>
</div>

How do I trigger a custom javascript event when a checkbox is selected via a jQuery script that selects all checkboxes on a page?

I'm currently working on a photography store website. Customers will be allowed to view photosets ranging from 100-500 images on a page. I want those customers to be able to click a "Select All" button (or other element) that checks all the checkboxes on the page. I am currently using jQuery to successfully accomplish this "Select All" feature after researching here on Stack Overflow.
Currently, the code that I am working with puts a checkbox on each image in the photoset. If the user clicks the checkbox, it triggers a custom event. However, I want the checkbox state of being checked (or the change from being unchecked to checked) to trigger the event, not the click. If the click triggers the event, the Select All feature I have using jQuery fails to work, since jQuery isn't "clicking" each of the checkboxes on the page, only changing the checkbox to selected. This means that the custom event doesn't load.
The code that currently works to trigger the event I need by clicking (which I do not want to do) the checkbox is:
$('.select-product').on('click', this.QuickOrder.loadProduct);
The code I am trying to develop isn't working, but it goes something like:
$('.select-product').change(function(){
var isChecked = $(this).is(':checked');
if(isChecked) {
this.QuickOrder.loadProduct;
}
});
I've used the .change() function after researching and finding that the change function registers the change in the condition of the checkbox. When this condition changes to true, I want QuickOrder.loadProduct to trigger. After that, everything should work.
Here is my jQuery "Select All" script for reference:
$(document).ready(function() {
$("#select_all").change(function(){
if(this.checked){
$(".select-product").each(function(){
this.checked=true;
})
}else{
$(".select-product").each(function(){
this.checked=false;
})
}
});
$(".select-product").click(function () {
if (!$(this).is(":checked")){
$("#select_all").prop("checked", false);
}else{
var flag = 0;
$(".select-product").each(function(){
if(!this.checked)
flag=1;
})
if(flag == 0){ $("#select_all").prop("checked", true);}
}
});
});
Any ideas on how to make this happen? Thank you!
As explained in Why isn't my checkbox change event triggered?:
The change event does not fire when you programmatically change the value of a check box.
Below I give two solutions (the first is from the aforementioned link):
1: Explicitly trigger the change event after changing the checkbox setting.
this.checked = true;
$(this).trigger('change');
2: Just programmatically delegate to the click event.
$(this).trigger('click');
Demo:
window.loadProduct = function(id) { alert('loadProduct() called on #'+id+'.'); };
// propagate select-all checkbox changes to all individual checkboxes
$("#select_all").change(function() {
if (this.checked) {
$(".select-product").each(function() {
// original code
//this.checked = true;
// solution #1: explicitly force a change event
this.checked = true;
$(this).trigger('change');
// solution #2: trigger click
//$(this).trigger('click');
});
} else {
$(".select-product").each(function() {
this.checked = false;
});
} // end if
});
// propagate individual checkbox changes back to the select-all checkbox
$(".select-product").click(function() {
if (!$(this).is(":checked")) {
$("#select_all").prop("checked", false );
} else {
var flag = 0;
$(".select-product").each(function() {
if (!this.checked)
flag = 1;
});
if (flag == 0) {
$("#select_all").prop("checked", true );
} // end if
} // end if
});
// call loadProduct() for any change of an individual checkbox
$('.select-product').change(function() {
var isChecked = $(this).is(':checked');
if (isChecked) {
loadProduct(this.id);
} // end if
});
.select_container {
margin-bottom:8px;
}
.img_container {
display:flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select_container">
<input id="select_all" type="checkbox"/>
</div>
<div class="img_container">
<div>
<div><img src="https://www.gravatar.com/avatar/4fa45261dec56004145c653832504920?s=128&d=identicon&r=PG&f=1"/></div>
<input id="check1" class="select-product" type="checkbox"/>
</div>
<div>
<div><img src="https://www.gravatar.com/avatar/fc03f6eed7d4d5e3233c5dde9f48480d?s=128&d=identicon&r=PG&f=1"/></div>
<input id="check2" class="select-product" type="checkbox"/>
</div>
<div>
<div><img src="https://www.gravatar.com/avatar/fd882c2b5e410936a4a607b2e87465d9?s=128&d=identicon&r=PG&f=1"/></div>
<input id="check3" class="select-product" type="checkbox"/>
</div>
</div>

condition on radio button onclick, if false don't check

onclick of one radio button i have to check one condition if true i have to check it or restore to same old status,
html
<input type="radio" name="test" id="radio0" onclick="myFunction()" checked />
<input type="radio" name="test" id="radio1" onclick="myFunction()" />
<input type="radio" name="test" id="radio2" onclick="myFunction()" />
JS
globalCondition = false;
function myFunction()
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}
As I said in comment return in the function will not do anything as you're not returning the function value in the in-line code.
Although the other solutions offered are correct, to keep your code unobtrusive, you should not have inline JS at all (remove the onclick='s).
I realize the question was not tagged jQuery, but maybe it should have been: Instead on onclick you should use a jQuery event handler, selecting only the set of radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/KVwL3/1/
globalCondition = false;
$(function(){
$("[name=test]").click(function(e){
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
return false;
// or
e.preventDefault();
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
});
});
Notes:
DOM ready event:
$(function(){ YOUR CODE HERE }); is a shortcut for $(document).ready(function(){ YOUR CODE HERE});
Selectors
If an attribute [] selector = value contains special characters it needs to be quoted:
e.g.
$('[name="IstDynamicModel[SD_WO_CREATE]"]')
There are any number of selectors that will choose just the three radio buttons. As this is a simple one-off connection, at startup, there is no real speed difference between any options, but you would normally try and make the selector specific in ways that might make use of various lookup tables available to the browser:
e.g.
$('input[type=radio][name="IstDynamicModel[SD_WO_CREATE]"]')
This will be slightly faster as it will reduce the slowest check (the name=) to only radio inputs.
try this:
globalCondition = false;
function myFunction(e)
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
e.preventDefault();
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}
USe like this
<input type="radio" name="test" id="radio1" onclick="return myFunction()" />
javascript
globalCondition = false;
function myFunction(e)
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
return true;
}
else
{
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}

Categories