DotNetCurry Logo

jQuery Checkbox and Radio Button Miscellaneous Tips

Posted by: Suprotim Agarwal , on 6/8/2015, in Category jQuery and ASP.NET
Views: 29123
Abstract: Checkboxes and RadioButton’s are one of the most frequently used Controls in any HTML form. This article will demonstrate how to use jQuery to perform common operations with these controls.

If you are working on a HTML form, the chances are very  high that you will be using Checkboxes and RadioButton’s on your page. This article will demonstrate how to perform common operations with these controls. I have also written an article on  jQuery Input Control (TextBox) Performance Tips  in case you are working with the TextBox control.

Note (self-plug): If you are working on Checkbox and RadioButton controls in an ASP.NET Page (especially Master Pages), I have written an Ebook on using jQuery with ASP.NET that shows how to solve challenges associated with ASP.NET Client-Side Development. You may consider buying the book to reduce your development time.

Let us get started:

1. Programmatically check a CheckBox state and change its state

To check the CheckBox state, use the .is() method:

$("#cb2").is(":checked");

To set a checkbox to checked state, use the following:

$('#cb2').prop('checked', true);

Here we are using prop() to explicitly set the checked property of the checkbox, in our case a checkbox with id=cb2.

As you might have guessed, to uncheck the checkbox, use:

$('#cb2').prop('checked', false);

The same way, you can set the checked property of a radio button too. 

 

2. Retrieve Selected Value of a RadioButton

Let us say, you want to retrieve the selected value of a RadioButton. Here’s how to do it:

$("input:radio").click(function () {
     $("#selRadio").text($(this).val());
})

selRadio is a paragraph element and we are setting it’s text property to the val() of the selected Radio button.

For those who are wondering why have I used .click() here instead of using .on('click', ..), just remember click() is just a shortcut for .on( "click", handler ).

Live Demo: http://www.jquerycookbook.com/demos/S2-Input Controls/9.6-InputMiscFunctions.html 

 

3. Retrieve Selected Option in a RadioButtonGroup

Radio buttons are almost always used in groups. Create a new HTML file called ‘InputMiscFunctions.html’ and write the following markup:

<body>
    <input type="radio" name="group1" value="Milk" /> Milk<br />
    <input type="radio" name="group1" value="Butter" /> Butter<br />
    <input type="radio" name="group1" value="Cheese" /> Cheese<br />
    <p id="status" />
</body>

All the radiobuttons have the same name, thereby keeping it in a group. To retrieve selected option in a RadioButtonGroup, use the following:

$(function () {
    var rGrp = $("input[name=group1]");
    rGrp.click(function () {                
        var checkedRadio = rGrp.filter(":checked");
        $("#status").text(checkedRadio.val());
    });
});

To get the value of a selected radio button in a group, you first need to access all the radio elements in the group. This is done using var rGrp = $("input[name=group1]");

When the user clicks on a radiobutton, find out which one is selected using rGrp.filter(":checked"); and then get the value attribute from that object using val() and display it in a paragraph.

Run the example and this what you get:

radiogroup-selected

Setting the checked value of individual radio buttons works the same way as check boxes.

Live Demo: http://www.jquerycookbook.com/demos/S2-Input Controls/9.7-InputMiscFunctions.html 

 

4. Retrieve and Display all Selected CheckBox Values

Let us say you want to display all selected checkbox values in a paragraph and also update the paragraph text once the user deselects some values. Create a new HTML file called ‘InputMiscFunctions.html‘ and add the following markup:

<body>
    <p id="checkBoxes">
        <input type="checkbox" id="cb1" value="1"/>
        <label for="Checkbox1">Option One</label>
        <br />
        <input type="checkbox" id="cb2" value="2" />
        <label for="Checkbox2">Option Two</label>
        <br />
        <input type="checkbox" id="cb3" value="3" />
        <label for="Checkbox3">Option Three</label>
        <br />
        <input type="checkbox" id="cb4" value="4" />
        <label for="Checkbox4">Option Four</label>
        <br />
    </p>
    <p id="status"/>
</body>

Observe that there is a label placed right after each checkbox. We will be reading the label’s value here. Use this code to display selected checkbox values

$(function () {
    var cb = $("#checkBoxes input[type='checkbox']");
    cb.on('click', function () {
        var selected = [];
        cb.each(function () {
            if (this.checked) {
                selected.push($(this).next().text());
            }
        });
        $("#status").text(selected.join(','));
    });
});

The selector $("#checkBoxes input[type='checkbox']") restricts us to all checkboxes inside the paragraph checkBoxes. Whenever a checkbox is clicked, we loop through each checkbox using .each(), and for the ones that are checked; add its label text to the selected array. Since this represents the current checkbox element and the label is placed right after each checkbox, we use $(this).next().text() to read its value. join() is our regular Array.join function. It converts the selected array object to a string, putting the comma (,) between each element. The result is assigned to the text() method of the paragraph status.

Save the ‘InputMiscFunctions.html’ file and view it in a browser. Click on the checkboxes and the paragraph will display all selected checkbox values.

checkbox-selected

In a previous article jQuery Input Control (TextBox) Performance Tips  we used map() to traverse the elements, and here I am showing an alternate way using each(). To know the difference between the two, check the previous article.

Live Demo: http://www.jquerycookbook.com/demos/S2-Input Controls/9.8-InputMiscFunctions.html 

 

5. Transform a RadioButton to a CheckBox

To transform a radiobutton to a checkbox, use prop()

$("#btnConvert").on('click', function () {
    $('input:radio').prop('type', 'checkbox');
});

On the click of the button, we are using prop() to change the radiobutton element’s type property from radio to checkbox. In case you are wondering why did I use prop() here instead of attr(), I have explained in my article Important Tips Every jQuery Developer Should Know that if you want to setup the default value for an HTML’s tag attribute, use attr(). However when you are setting properties on the window or document objects, you should always use prop(). Check the link I just shared to read more about it.

Live Demo: http://www.jquerycookbook.com/demos/S2-Input Controls/9.9-InputMiscFunctions.html

If you liked this article, take a look at a new jQuery book The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!