0

Being out of programming for several years, I'm attempting what I thought would be a relatively basic HTML form, and have come across several things I no longer know how to do.

First, I have a 5x10 table of checkboxes. Whenever any box is checked, I would like the same code to execute, (If 4 checkboxes are already checked, throw an error, otherwise continue).

How do I get this code to run on all checkboxes without needing to add an "onclick" to every individual button?

Second, when a checkbox is selected, I would like to change the background color of the element it is contained within.

And finally, is there an easy way to replace the checkbox image with a numbered ball or labeled button?

As requested, my code, so far, is here: https://www.dropbox.com/s/mem6egamsojq18g/DrawTicket.html

NickSentowski
  • 820
  • 13
  • 27

2 Answers2

2

Well, here is a bit hackish, pure JS version. Should get you started fine...

HTML:

<table id="table">
    <tr>
        <td><input type="checkbox"/></td>
        <td><input type="checkbox"/></td>
    </tr>
     <tr>
        <td><input type="checkbox"/></td>
        <td><input type="checkbox"/></td>
    </tr>
     <tr>
        <td><input type="checkbox"/></td>
        <td><input type="checkbox"/></td>
    </tr>
</table>

CSS, just for visual aid:

td {
    border: 1px solid #cccccc;
}

td.checked {
    background: #ff0000;
}

JS:

var handler = function(event) {
    if(event.target.parentNode.className.indexOf('checked') < 0 ) {
        event.target.parentNode.className += ' checked';
    } else {
        event.target.parentNode.className = 
                event.target.parentNode.className.replace(' checked', '');
    }
};

var table = document.getElementById('table');
table.addEventListener('click', handler);

And JSFiddle to play with.

P.S.

As for replacing it with image - there is plenty of solutions online, most of them are not cross browser - see here: How to style checkbox using CSS?

Community
  • 1
  • 1
ZenMaster
  • 12,363
  • 5
  • 36
  • 59
1

I think the easier way is using jquery so: In the head section (or as last element in the body)

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
  $(function(){
    $('input:checkbox').click(function(){
      if ($(this).is(':checked')) {
        $(this).parent().css('background-color', 'green');
      } else {
        $(this).parent().css('background-color', 'white');
      }
    });
  });
</script>

I'm thinking a good solution for the third question

Aguardientico
  • 7,641
  • 1
  • 33
  • 33