Dojo FAQ: How do you set a default selected RadioButton?

By on February 19, 2014 2:41 pm

The widgets provided in Dojo’s Dijit library include not only advanced widgets not provided by HTML, but also enhanced versions of the basic HTML form elements, like <input>. Dijit’s dijit/form/RadioButton provides the same basic functionality as an HTML radio button, so let’s look at how you set one to be checked by default.

HTML input elements use the checked attribute:

<input type="radio" name="colors" value="green" checked="checked"> Green
<input type="radio" name="colors" value="red"> Red

This results in the following:

The RadioButton Dijit will receive the value of the same attributes when defined declaratively (via markup):

<input type="radio" name="colors" value="green" checked="checked"
	data-dojo-type="dijit/form/RadioButton"> Green
<input type="radio" name="colors" value="red"
	data-dojo-type="dijit/form/RadioButton"> Red

As you can see, this is the same markup as before with the addition of the data-dojo-type attribute so that Dojo’s parser will convert the element to a RadioButton Dijit. The parser is also the code that scans the DOM for attributes and passes those values into a widget that is instantiated from HTML markup.

However, keep in mind that if you create a RadioButton programmatically (via JavaScript), you will need to specify the attribute values explicitly in JavaScript, rather than in a placeholder DOM node:

require(['dijit/form/RadioButton', 'dojo/domReady!'
], function (RadioButton) {
	new RadioButton({
		checked: true,
		value: 'green',
		name: 'colors'
	}, 'radioColorGreen');

	new RadioButton({
		value: 'red',
		name: 'colors'
	}, 'radioColorRed');

Here’s the dijit/form/RadioButton example in action:

Learning more

SitePen has a number of excellent Dojo tutorials we’ve created for learning more about Dojo and Dijit. We also cover Dijit in depth in our Dojo workshops offered throughout the US, Canada, and Europe, or at your location. We also provide expert JavaScript and Dojo support and development services, to help you get the most from JavaScript and Dojo.