2

I use the following code on jsfiddle.net and the live preview works. Run my own local copy, and nothing...

Checkboxes should change on radiobutton click.

jsfiddle preview: http://jsfiddle.net/XqFDN/

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
    <script>
        jQuery('#3day').click(function () {
            jQuery('#mon , #tue , #wed').attr('checked', true);
        });
        jQuery('#2day , #1day').click(function () {
            jQuery('#mon , #tue , #wed').attr('checked', false);
        });
    </script>
</head>

<body>
    <form>
        <input type="radio" name="passes" value="3day" id="3day" />3-Day
        <input type="radio" name="passes" value="2day" id="2day" />2-Day
        <input type="radio" name="passes" value="1day" id="1day" />1-Day
        <br />

        <input type="checkbox" name="mon" value="mon" id="mon" />Mon
        <input type="checkbox" name="tue" value="tue" id="tue" />Tue
        <input type="checkbox" name="wed" value="wed" id="wed" />Wed
        <br />
    </form>
</body>
</html>
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
mpdc
  • 3,440
  • 4
  • 20
  • 44
  • Under "choose framework" in your fiddle, you've selected "no wrap (body)". The code you've pasted is equivalent of the option "no wrap (head)". – David Hedlund Jan 14 '13 at 12:47
  • 1
    Did you know that you only have to write `jQuery` in its long form once? By wrapping your code in `(function($) { .... })(jQuery);`, you can use `$` no matter if `noConflict` has been used or not. // And you should use `.prop('checked', true_or_false)` instead of `attr` – ThiefMaster Jan 14 '13 at 12:48
  • Didn't even occur to me to use .prop as .attr worked fine - thanks. – mpdc Jan 14 '13 at 13:05
  • 1
    Duplicate of [Why does jQuery or a DOM method such as `getElementByID` not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). – Felix Kling Jan 14 '13 at 13:22
  • Duplicate of [How do I put codes from jsfiddle.net into my website?](http://stackoverflow.com/q/4936870/1048572) – Bergi Sep 11 '16 at 11:26

1 Answers1

8

You need to wrap your jQuery code in a document ready handler. Try this:

<script type="text/javascript">
    jQuery(function() { // alternative: $(document).ready(function() {
        jQuery('#3day').click(function () {
            jQuery('#mon , #tue , #wed').attr('checked', true);
        });
        jQuery('#2day , #1day').click(function () {
            jQuery('#mon , #tue , #wed').attr('checked', false);
        });
    });
</script>

This enclosure ensures that the code within it is run when the DOM has been loaded. Currently, your code is trying to attach click events to elements which do not yet exist.

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303