Select only one checkbox in a group

This snippet will:

Allow grouping like Radio buttons
Act like Radio
Allow unselecting all

// the selector will match all input controls of type :checkbox
// and attach a click event handler
$(“input:checkbox”).on(‘click’, function() {
// in the handler, ‘this’ refers to the box clicked on
var $box = $(this);
if ($box.is(“:checked”)) {
// the name of the box is retrieved using the .attr() method
// as it is assumed and expected to be immutable
var group = “input:checkbox[name='” + $box.attr(“name”) + “‘]”;
// the checked state of the group/box on the other hand will change
// and the current value is retrieved using .prop() method
$(group).prop(“checked”, false);
$box.prop(“checked”, true);
} else {
$box.prop(“checked”, false);
}
});

src=”https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js”>

Fruits
type=”checkbox” class=”radio” value=”1″ name=”fooby[1][]” />Kiwi
type=”checkbox” class=”radio” value=”1″ name=”fooby[1][]” />Jackfruit
type=”checkbox” class=”radio” value=”1″ name=”fooby[1][]” />Mango

Animals
type=”checkbox” class=”radio” value=”1″ name=”fooby[2][]” />Tiger
type=”checkbox” class=”radio” value=”1″ name=”fooby[2][]” />Sloth
type=”checkbox” class=”radio” value=”1″ name=”fooby[2][]” />Cheetah

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s