Search code examples
javascriptjquerydojo

How to get a radio group's selected value in Dojo


I need to do a project using Dojo and I am totally confused how to deal with a group of radios. Consider an example like following; it is easy to get the selected value by using:

$('input[name=map]').on('change', function() {
    console.info($(this).val());
});

How can I do this in Dojo?

require([ "dojo/dom",
          "dojo/on",
          "dojo/domReady!"], function(dom, on) {

   //------?

});

// jQuery way

$('input[name=map]').on('change', function() {
    console.info($(this).val());
});

// Dojo Way ???
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.11.2/dojo/dojo.js"></script>

<input type="radio" name="map" value="dark"> Dark<br>
<input type="radio" name="map" value="streets"> Street<br>
<input type="radio" name="map" value="terrain"> Terrain


Solution

  • You need to use dojo/query for it. This should do it.

        // Dojo Way:
     		require(["dojo/on", "dojo/query", "dojo/domReady!"],
    		function(on, query) {
    			query("[name='map']").map(function(radio){
    				on(radio, "change", function(evt){
    					console.log(this.value);
    				})
    			})
    	});
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.11.2/dojo/dojo.js"></script>
    
    <input type="radio" name="map" value="dark"> Dark<br>
    <input type="radio" name="map" value="streets"> Street<br>
    <input type="radio" name="map" value="terrain"> Terrain