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

0

2 Answers 2

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.sstatic.net/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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.