2

I'm making a grid of divs that can be toggled on and off. I need to post the values of these toggled divs to a database.

Currently I have jQuery waiting for clicks on the divs and then changing checkbox values on a hidden checkbox element...

$('.icon').click(function(){
    var checkValue = $(this).attr("data-c");
    // Then tick hidden checkbox where data-c = checkbox
});

As I end up posting this data with ajax, is there a better way to do this?

Here's what it looks like:
example

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
themollusk
  • 440
  • 4
  • 10

2 Answers2

2

You actually don't need JS.
Use a <label> elements to wrap your checkbox and a span.
Change the style of that inner span using the input:checked next sibling selector +:

label.icon span{
  cursor:  pointer;
  display: inline-block;
  width:   75px;
  height:  75px;
  background:url(https://i.stack.imgur.com/ceycQ.jpg) no-repeat;
  border:  3px solid #0186C9;
  border-radius: 12px;
}
label.icon input{ /* hide the checkbox */
  position:   absolute;
  visibility: hidden;
}
label.icon input:checked + span{ /* when input is checked */
  background-position: 0 -75px;
}
<form action="">

  <label class="icon">
    <input type="checkbox" name="dog">
    <span></span>
  </label>

</form>

on form submit you'll submit all the correct data without a single line of JS

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • 1
    Awesome. Exactly what I was after. Thanks for interpreting my not so great explanation! Ever since I've become somewhat competent with JS I've been really over using it. This is a good reminder to be a bit more conservative. – themollusk May 04 '15 at 00:09
1

I've found a similar question here: Jquery Use Image As CheckBox

As an alternative to storing the value in a check box you could store it in a object? For example:

window.icons = {};
$('.icon').click(function() {
    var id = $(this).data('identifier');
    window.icons[id] = !!window.icons[id];
});

Also check out this example for a similar use http://jsfiddle.net/bdTX2/

Community
  • 1
  • 1
filype
  • 8,034
  • 10
  • 40
  • 66