0

I'm trying to incorporate this here with checkboxes on Rails.

My HTML looks like this:

<div>
  <input id="reservation_item_ids_" name="reservation[item_ids][]" type="checkbox" value="17">

RCF, 32.0 €/vrk

And the code like this (I'm using jQuery instead of $ to try to avoid conflicts with prototype, which is used by default in Rails 3):

    console.log("Initialize!");
jQuery("input[type=checkbox]").click(function() {
    console.log("Clicked!");

   var total = 0;

    jQuery("input[type=checkbox]:checked").each(function() {
    total += parseFloat(jQuery(this).val());
    });

    jQuery("#totalSum").val(total);
});

My console gives me only this:

Initialize!

..regardless of how much I click the checkboxes.. I also tried replacing "input[type=checkbox]" with "#reservation_item_ids" with no luck.

No errors, no clues whatsoever..

Community
  • 1
  • 1
Timo Herttua
  • 5
  • 1
  • 3
  • [Works for me](http://jsfiddle.net/vkbdP/). What are you doing to ensure the DOM is loaded before your code runs? – user113716 Jul 17 '11 at 20:18
  • ...there are a number of ways to do this, but one possible solution is to wrap your code in a handler that is sent to jQuery's `ready()` method. `jQuery(function() { /* ...your code... */ });` – user113716 Jul 17 '11 at 20:20
  • double check that id's are unique on the page – cinek Jul 17 '11 at 21:29
  • question about jsFiddle: does it behave the same as a browser in terms of the 'ready' method? If the question asker is having timing issues then would it be uncovered with jsFiddle? Regardless, it's a very cool site... – jaydel Jul 18 '11 at 01:04

3 Answers3

2

You need to do this:

jQuery(document).ready(function($) {
    jQuery("input[type=checkbox]").click(function() {
        alert('It works!')
    })
})
thenengah
  • 42,557
  • 33
  • 113
  • 157
0

Is this dynamic HTML? Have you tried live()?

jQuery("input[type=checkbox]").live('click', function() {

some systems don't like the "click" method so much.

Jeremy Holovacs
  • 22,480
  • 33
  • 117
  • 254
0

Your above code is not the problem, it works fine for me. I setup a test page with only the following in it:

<form>
    <input id="num1" type="checkbox" value="1"><br />
    <input id="num2" type="checkbox" value="1"><br />
    <input id="num3" type="checkbox" value="1"><br />
    <input id="num4" type="checkbox" value="1"><br />

    <input type="submit" value="Submit" />
</form>

I even alerted out your total, it works just fine! It's probably the case that the selector is not picking up your checkboxes due to the way you've set them up. Can you copy/paste your form code?

user839124
  • 65
  • 1
  • 1
  • 4