简体   繁体   中英

convert Checkbox into radio button using javascript?

I am trying to convert checkbox into radio button which is working partially , but not deselecting previous selected radio button.I am looking solution to show one button at a time as a selected.

var layers = {
    'Esri_WorldImagery': Esri_WorldImagery.addTo(this.baseMap),
    'World_Topo_Map': World_Topo_Map//.addTo(this.baseMap)
};

var layerHtml = '<ul class="fa-ul">';
for (var key in layers) {
    if (layers.hasOwnProperty(key)) {
        var state = this.baseMap.hasLayer(layers[key]) ? 'checked="checked"' : '';
        //layerHtml += '<li><label><input type="checkbox" ' + state + ' value="' + key + '" >' + key + '</label>';
        layerHtml += '<li><label><input type="radio" ' + state + ' value="' + key + '" >' + key + '</label>';
    }
}

layerHtml += '</ul>';
var widget = $('<div id="layer-control" class="sidebar-widget">' + layerHtml + '</div>');

widget.on('click', 'input[type="radio"]', function (e) {

    var was_Active = $(this).prop('checked');
    var value = $(this).val();
    if (was_Active) {
        layers[value].addTo(self.baseMap);
    }
    else {
        self.baseMap.removeLayer(layers[value]);
    }
});

First, regarding the current code with radio elements, as @Aswin Ramesh has told you, yo should add the name attribute. From MDN :

A radio group is defined by giving each of radio buttons in the group the same name. Once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group.

Besides the shape (circle vs square) that's the only difference between the radio and checkbox elements. So consider that checkboxes that behave like radio buttons might be confusing for the user.

That said, if you really want to replicate that functionality on checkboxes, use JavaScript to deselect all the elements but the one which raised the click event.

 $('#checkboxes').on('click', ':checkbox', function(e) { $('#checkboxes :checkbox').each(function() { if (this != e.target) $(this).prop('checked', false); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="radios"> <input type="radio" name="rOptions" value="radio1" checked> <input type="radio" name="rOptions" value="radio2"> <input type="radio" name="rOptions" value="radio3"> </div> <div id="checkboxes"> <input type="checkbox" value="checkbox1" checked> <input type="checkbox" value="checkbox2"> <input type="checkbox" value="checkbox3"> </div>

Note : you forgot to close the <li> tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM