Don W.
Don W.

Reputation: 560

use Dojo to programmatically set checkboxes checked

The codes below returns Uncaught TypeError: Cannot set property 'checked' of null. what is the correct way to programmatic set checkbox as checked?

        array.forEach(this._getAllCheckBoxIDs(), function(item){
            dom.byId(item).checked = true;
        }, this);

Upvotes: 1

Views: 4850

Answers (2)

Vikash Pandey
Vikash Pandey

Reputation: 5443

Well, If you you have the collections of dojo checkboxes then I would suggest you to use registry.byId instead of dojo.byId because you need checkbox dojo widget along with it's domNode to update its attribute.

dojo class name:-

dijit/registry

Ex:-

// require registry class first
array.forEach(this._getAllCheckBoxIDs(), function(item){
     registry.byId(item).set("checked", true);
}, this);

for more details please click here...

Hoping this will help you :)

Upvotes: 0

GibboK
GibboK

Reputation: 73908

The following example shows a programmatic example on how to set property checked for a widget checkbox.

The script gets references of your checkboxes using dijit/registry opposite to querying the DOM.

Instead of setting a property directly for your widget like this:

dom.byId(item).checked = true;

I would suggest using a setter like:

widgetReference.set('checked', true);

This will allow the widget life-cycle to work properly.

Live example here:

https://jsfiddle.net/femtf4uh/

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) {

    }
  }, "checkBox0").startup();
  new CheckBox({
    id: "checkBox1",
    name: "checkBox1",
    value: "option1",
    checked: false,
    onChange: function(event) {

    }
  }, "checkBox1").startup();

  var markCheckAll = function() {
    registry.toArray().forEach(function(widget) {
      if (widget.type === 'checkbox'){
        widget.set('checked', true);
      }
    });
  };
  markCheckAll();

});

<input id="checkBox0" />
<label for="checkBox">Option 0</label>
<br>
<input id="checkBox1" />
<label for="checkBox">Option 1</label>
<br>

Upvotes: 1

Related Questions