Riz
Riz

Reputation: 215

How to change checkboxes to behave like radio button using jquery?

Basically its an availability schedule calendar. Seven checkboxes has the same class. Then other seven boxes has the same class. There are total of 49 checkboxes and total 7 classes. So I want these checkboxes to behave like radio buttons. i.e No two checkboxes of same class can be checked at a time. For example, If someone checks the box with class 'earlyMorning' . When he checks the other checkbox with the same class the first one should be unchecked. Here is my html. Right now writing only 21 checkboxes.

<table> <tr>
            <th>Early Morning<br /><small>6am-9am</small></th>
                <td><input type="checkbox" class="earlyMorning" name="field_807[]" id="field_871_0" value="Early Morning 6am-9am Monday" style="display: none;"></td>
                <td><input type="checkbox" class="lateMorning" name="field_807[]" id="field_872_1" value="Early Morning 6am-9am Tuesday" style="display: none;"></td>
                <td><input type="checkbox" class="earlyAfternoon" name="field_807[]" id="field_873_2" value="Early Morning 6am-9am Wednesday" style="display: none;"></td>
                <td><input type="checkbox" class="lateAfternoon" name="field_807[]" id="field_874_3" value="Early Morning 6am-9am Thursday" style="display: none;"></th>
                <td><input type="checkbox" class="earlyEvening" name="field_807[]" id="field_875_4" value="Early Morning 6am-9am Friday" style="display: none;"></td>
                <td><input type="checkbox" class="lateEvening" name="field_807[]" id="field_876_5" value="Early Morning 6am-9am Saturday" style="display: none;"></td>
                <td><input type="checkbox" class="overnight" name="field_807[]" id="field_877_6" value="Overnight 12am-6am Sunday" style="display: none;"></td>
            </tr>

            <tr>
            <th>Late Morning<br /><small>9am-12pm</small></th>
                <td><input type="checkbox" class="earlyMorning" name="field_807[]" id="field_878_7" value="Late Morning 9am-12pm Monday" style="display: none;"></td>
                <td><input type="checkbox" class="lateMorning" name="field_807[]" id="field_879_8" value="Late Morning 9am-12pm Tuesday" style="display: none;"></td>
                <td><input type="checkbox" class="earlyAfternoon" name="field_807[]" id="field_880_9" value="Late Morning 9am-12pm Wednesday" style="display: none;"></td>
                <td><input type="checkbox" class="lateAfternoon" name="field_807[]" id="field_881_10" value="Late Morning 9am-12pm Thursday" style="display: none;"></th>
                <td><input type="checkbox" class="earlyEvening" name="field_807[]" id="field_882_11" value="Late Morning 9am-12pm Friday" style="display: none;"></td>
                <td><input type="checkbox" class="lateEvening" name="field_807[]" id="field_883_12" value="Late Morning 9am-12pm Saturday" style="display: none;"></td>
                <td><input type="checkbox" class="overnight" name="field_807[]" id="field_884_13" value="Overnight 12am-6am Sunday" style="display: none;"></td>
            </tr>

            <tr>
            <th>Early Afternoon<br /><small>12pm-3pm</small></th>
              <td><input type="checkbox" class="earlyMorning" name="field_807[]" id="field_885_14" value="Early Afternoon 12pm-3pm Monday" style="display: none;"></td>
              <td><input type="checkbox" class="lateMorning" name="field_807[]" id="field_886_15" value="Early Afternoon 12pm-3pm Tuesday" style="display: none;"></td>
           <td><input type="checkbox" class="earlyAfternoon" name="field_807[]" id="field_887_16" value="Early Afternoon 12pm-3pm Wednesday" style="display: none;"></td>
             <td><input type="checkbox" class="lateAfternoon" name="field_807[]" id="field_888_17" value="Early Afternoon 12pm-3pm Thursday" style="display: none;"></th>
               <td><input type="checkbox" class="earlyEvening" name="field_807[]" id="field_889_18" value="Early Afternoon 12pm-3pm Friday" style="display: none;"></td>
             <td><input type="checkbox" class="lateEvening" name="field_807[]" id="field_890_19" value="Early Afternoon 12pm-3pm Saturday" style="display: none;"></td>
                <td><input type="checkbox" class="overnight" name="field_807[]" id="field_891_20" value="Overnight 12am-6am Sunday" style="display: none;"></td>
            </tr></table>

I have found a nice example here but its not working in my case. make checkbox behave like radio buttons with javascript

Based on the above tutorial, I tried this but not working

$(".earlyMorning").each(function()
{
    $(this).change(function()
    {
        $(".earlyMorning").prop('checked',false);
        $(this).prop('checked',true);
    });
});

Upvotes: 3

Views: 7383

Answers (6)

G-Cyrillus
G-Cyrillus

Reputation: 105903

I would propose another approach, that does not depend on javascript.


<edit> I did not notice before comment of @pebbl , that class where used as group name. In order to keep this form working as expected , class attributes value, should replace and be moved to the name attribute, value. On server side , update routine to a regular way of getting input radio value. DEMO with name attributes updated to your needs

These are advise only. </edit>


DEMO or you can download stand alone html & css file here


First, do use te radio input , they are made for what you want to do and form will not depend on javascript to be efficient.

Then , use CSS to style a usable checkbox for younger browser.

To make sure older browser do not hide your form elements, use advanced selector.

In order to be able to make CSS checboxes, you need to add some extra markup, a neutral inline element to each input you want to see replaced.

prepare the HTML:


turn <td><input type="radio"/></td>

into <td><input type="radio"/><span></span></td>


For the css part.


You can use thoses selectors (conbined to class, id, data-attribute or use anyother advanced selectors) :

  • [type="radio"]
  • [type="radio"]+
  • [type="radio"]:checked +
  • [type="radio"]+span::before.

    Older browser will not style anything .


DEMO or you can download stand alone html & css file here


What's the point ?

If your page is missing either javaScript/jQuery or CSS sheet , your formular will still be efficient and usable.I guess this is what matters the most.

You can see radio input and CSS generated boxes as a fallback to each other.

Upvotes: 1

Pebbl
Pebbl

Reputation: 36005

Here is a pure js solution, although I have to agree with Svenskunganka, your class names don't make sense in terms of your table headers.

http://jsfiddle.net/nE75S/

The following will work across all modern browsers, and some older, however to get this working in older versions of Internet Explorer you will either need a polyfill for addEventListener, or implement conditionals to use attachEvent instead.

For more information check out this StackOverflow QA, or search Google:

Firefox attachEvent and addEventListener issues with both

Obviously it should be noted the following code only groups the inputs after page load. If you wish to have a quicker reaction — i.e. trigger after DOM readiness, or you wish the code to work with AJAXed content I'd recommend using a library like jQuery and use the .on() delegation method for your event listeners.

window.addEventListener('load', function(){
    var inps = document.getElementsByTagName('input'), inp;
    var i, l = inps.length, c, groups = {};
    /// react to a particular class-named group of inputs
    var react = function(e){
      var inp = e.target, group = groups[inp.className], i, l, otherinp;
      if ( group ) {
        for ( i=0, l=group.length; i<l; i++ ) {
          otherinp = group[i];
          if ( inp !== otherinp ) {
            otherinp.checked = false;
          }
        }
      }
    };
    /// group inputs based on className
    for ( var i=0; i<l; i++ ) {
        if ( (inp = inps[i]) && inp.type == 'checkbox' ) {
            switch( (c = inp.className) ) {
              case 'earlyMorning':
              case 'lateMorning':
              case 'earlyAfternoon':
              case 'lateAfternoon':
              case 'earlyEvening':
              case 'lateEvening':
              case 'overnight':
                !groups[c] && (groups[c] = []);
                groups[c].push(inp);
                inp.addEventListener('change', react);
              break;
            }
        }
    }
});

Upvotes: 1

FelipeAls
FelipeAls

Reputation: 22171

As each group of checkbox is in the same table row, you can have a single script managing all the groups:

http://jsfiddle.net/ukmhW/

$("table").on("click", 'input[type="checkbox"]', function () {
    $(this).change(function() {
        // Up to TR, uncheck all the checkboxes in this row and check the one that was clicked
        $(this).parent().parent().find('input[type="checkbox"]').prop('checked',false);
        $(this).prop('checked',true);
    });
});

Upvotes: 1

webDa
webDa

Reputation: 106

My solution using jQuery:

        $(document).ready(function() {
            $('input').click(function() {
                var input_class = $(this).attr('class');

                $('.'+input_class).prop('checked', false);

                $(this).prop('checked', true);
            });
        });

On every click on a checkbox, all checkboxes with the same class get un-checked before checking the clicked element.

I hope this helps.

Upvotes: 4

Sven
Sven

Reputation: 5265

You'r class names were a bit misplaced, take a look at this fiddle: http://jsfiddle.net/44Zfv/345/

There's probably a cleaner way of doing this, instead of a function for each class name but as I don't know how your HTML resulted in that I cannot append the functions.

Your class names should look something like this instead:

<table> 
  <tr>
    <th>Early Morning<br /><small>6am-9am</small></th>
    <td><input type="checkbox" class="earlyMorning" name="field_807[]" id="field_871_0" value="Early Morning 6am-9am Monday"></td>
    <td><input type="checkbox" class="earlyMorning" name="field_807[]" id="field_872_1" value="Early Morning 6am-9am Tuesday"></td>
    <td><input type="checkbox" class="earlyMorning" name="field_807[]" id="field_873_2" value="Early Morning 6am-9am Wednesday"></td>
    <td><input type="checkbox" class="earlyMorning" name="field_807[]" id="field_874_3" value="Early Morning 6am-9am Thursday"></th>
    <td><input type="checkbox" class="earlyMorning" name="field_807[]" id="field_875_4" value="Early Morning 6am-9am Friday"></td>
    <td><input type="checkbox" class="earlyMorning" name="field_807[]" id="field_876_5" value="Early Morning 6am-9am Saturday"></td>
    <td><input type="checkbox" class="earlyMorning" name="field_807[]" id="field_877_6" value="Overnight 12am-6am Sunday"></td>
  </tr>
  <tr>
    <th>Late Morning<br /><small>9am-12pm</small></th>
    <td><input type="checkbox" class="lateMorning" name="field_807[]" id="field_878_7" value="Late Morning 9am-12pm Monday"></td>
    <td><input type="checkbox" class="lateMorning" name="field_807[]" id="field_879_8" value="Late Morning 9am-12pm Tuesday"></td>
    <td><input type="checkbox" class="lateMorning" name="field_807[]" id="field_880_9" value="Late Morning 9am-12pm Wednesday"></td>
    <td><input type="checkbox" class="lateMorning" name="field_807[]" id="field_881_10" value="Late Morning 9am-12pm Thursday"></th>
    <td><input type="checkbox" class="lateMorning" name="field_807[]" id="field_882_11" value="Late Morning 9am-12pm Friday"></td>
    <td><input type="checkbox" class="lateMorning" name="field_807[]" id="field_883_12" value="Late Morning 9am-12pm Saturday"></td>
    <td><input type="checkbox" class="lateMorning" name="field_807[]" id="field_884_13" value="Overnight 12am-6am Sunday"></td>
  </tr>
  <tr>
    <th>Early Afternoon<br /><small>12pm-3pm</small></th>
    <td><input type="checkbox" class="earlyAfternoon" name="field_807[]" id="field_885_14" value="Early Afternoon 12pm-3pm Monday"></td>
    <td><input type="checkbox" class="earlyAfternoon" name="field_807[]" id="field_886_15" value="Early Afternoon 12pm-3pm Tuesday"></td>
    <td><input type="checkbox" class="earlyAfternoon" name="field_807[]" id="field_887_16" value="Early Afternoon 12pm-3pm Wednesday"></td>
    <td><input type="checkbox" class="earlyAfternoon" name="field_807[]" id="field_888_17" value="Early Afternoon 12pm-3pm Thursday"></th>
    <td><input type="checkbox" class="earlyAfternoon" name="field_807[]" id="field_889_18" value="Early Afternoon 12pm-3pm Friday"></td>
    <td><input type="checkbox" class="earlyAfternoon" name="field_807[]" id="field_890_19" value="Early Afternoon 12pm-3pm Saturday"></td>
    <td><input type="checkbox" class="earlyAfternoon" name="field_807[]" id="field_891_20" value="Overnight 12am-6am Sunday"></td>
  </tr>
</table>

Upvotes: 1

xate
xate

Reputation: 6379

For example:

function Selection(elem)
{
  var elems = document.getElementsByTagName("input");
  var currentState = elem.checked;
  var elemsLength = elems.length;

  for(i=0; i<elemsLength; i++)
  {
    if(elems[i].type === "checkbox")
    {
       elems[i].checked = false;   
    }
  }

  elem.checked = currentState;
}​

<input type="checkbox" class="chkclass" onclick="Selection(this);" />
<input type="checkbox" class="chkclass" onclick="Selection(this);" />
<input type="checkbox" class="chkclass" onclick="Selection(this);" />
<input type="checkbox" class="chkclass" onclick="Selection(this);" />

So what are you doing here:

You just always uncheck the other elements, when one element is clicked. Like this, only 1 checkbox can be active at once and they behave like radio buttons.

Upvotes: 1

Related Questions