3

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);
    });
});
Community
  • 1
  • 1
Riz
  • 185
  • 3
  • 7
  • 14
  • 1
    How does your javascript code look like? – Sven Apr 17 '14 at 08:36
  • 2
    Why do you want to do this? Radio buttons and checkboxes are differetn for a reason - it's almost always better to use them for their intended purpose, especially for accessibility. – Jeff Apr 17 '14 at 08:38
  • Actually, I am limited. Its a php generated html and I have to make it to work like radio buttons. Actually I am working on buddypress and have to create a schedule calendar. – Riz Apr 17 '14 at 08:40
  • Is my answer, what you need óO? I'm not quite sure. – Xatenev Apr 17 '14 at 08:41
  • Works for me, although you've misplaced the class names a bit. Check the first ones vertically. http://jsfiddle.net/44Zfv/344/ – Sven Apr 17 '14 at 08:45
  • @Riz when you need a jquery solution, i will fix my answer – Xatenev Apr 17 '14 at 08:46

6 Answers6

4

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.

webDa
  • 106
  • 1
  • 6
  • Pebbl has also provided the solution but your solution is simple one. Just few lines of jquery. thanks – Riz Apr 18 '14 at 03:04
1

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.

Xatenev
  • 6,383
  • 3
  • 18
  • 42
  • WHAT is not working? What happens? You get any errors? – Xatenev Apr 17 '14 at 08:46
  • Dreamweaver error: "document current encoding can not correctly save all of the character with in the document.... – Riz Apr 17 '14 at 08:48
  • Lol, some problems with your encoding? Im not familiar with Dreamweaver but that does NOT sound like a code error. – Xatenev Apr 17 '14 at 08:49
  • 2
    What sort of Witchcraft is this? Don't use Dreamweaver to test your code, use a browser to test. Dreamweaver only tries to emulate a browser and won't always get it right. – CheckeredMichael Apr 17 '14 at 09:05
  • @Riz you should setup a local webserver, so you can check your code in a browser. – Xatenev Apr 17 '14 at 09:07
  • this code is working for me but with jquery library 1.5.2. I want it to be working with latest jquery 1.10.2. here is code $(".earlyMorning").each(function() { $(this).change(function() { $(".earlyMorning").attr('checked',false); $(this).attr('checked',true); }); }); – Riz Apr 17 '14 at 11:55
  • here is the working demo. Please tell me whats the problem. Why its not working with latest jquery library? – Riz Apr 17 '14 at 11:56
1

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>
Sven
  • 5,155
  • 29
  • 53
1

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);
    });
});
FelipeAls
  • 21,711
  • 8
  • 54
  • 74
1

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;
            }
        }
    }
});
Community
  • 1
  • 1
Pebbl
  • 34,937
  • 6
  • 62
  • 64
1

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.

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
  • I agree with your point about using the right tool for the job (more developers need to do this), but how do you propose keeping all inputs with `name="field_807[]"` whilst supporting each class-category needing to behave as a separate group? Currently your demo includes every input in one group, which is not what the OP requested. – Pebbl Apr 17 '14 at 11:01
  • @pebbl radio button are grouped via the name attribute, this is to be updated with the class value you in order to work. I did not noticed that he was as well abusing the use of the class value. – G-Cyrillus Apr 17 '14 at 11:28
  • so it would be like this, http://codepen.io/gc-nomade/pen/aFzBs/ and no need anymore on server side to catch wich field_807[] has been checked , just a regular use – G-Cyrillus Apr 17 '14 at 11:34
  • Much better +1 (and I agree, changing the design would be preferable). However this does make assumptions that the OP has the ability to change the server-side; which by their comments above appears not to be the case. – Pebbl Apr 17 '14 at 11:41
  • @pebbl yes, unfortunately, time was spent as well to have this form working on server side too :) – G-Cyrillus Apr 17 '14 at 11:46