views:

33

answers:

1

Hi guys,

I have the following code which enables a button when the checkbox is checked.

http://jsfiddle.net/ERfWz/1/

The following is a snippet from the code I have in my HTML page. It's much the same however for some reason it's not working. I think I may have been looking at it for too long.

<script type='text/javascript'>
$(function() {
  $('#agree').click(function() {
    var satisfied = $('#agree:checked').val();
    if (satisfied != undefined) $('#submit').removeAttr('disabled');
    else $('#submit').attr('disabled', 'disabled');
  });
});​
</script>



<form>
    <table>
    <td colspan="5"><input type="checkbox" id="agree" name="agree" />I have read and agree to the terms and 

    conditions</td>
                  </tr>
                  <tr>
                    <td colspan="5" align="center"><input name="Submit" type="submit" id="submit" disabled value="I Accept. 

    Submit"/>
                  <label>
                      <input name="reset" type="reset" id="reset" value="Reset" />
                      <input type="hidden" name="ip" value=" echo $REMOTE_ADDR; " />
                  </label></td>
                  </tr>
                    <tr>
                    <td>*Required Fields</td>
                    <td colspan="4"></td>
                  </tr>
                   <tr>
                    <td colspan="5"><h3></h3>
                     <p>&nbsp;</p></td>
                  </tr>
                </table>
            </fieldset>
            </form>
+5  A: 

You can also set disabled with true and false, so you can simplify it down to:

$(function() {
  $('#agree').change(function() {
    $('#submit').attr('disabled', !this.checked);
  });
});​

Test it out here, note there was also some invalid markup going on resulting in some cross-browser inconsistencies, it should look something like this:

<form>
  <table>
    <tr><td align="center"><input type="checkbox" name="agree" id="agree">I agree Terms and Conditions</td></tr>
    <tr><td align="center"><input type="submit" name="submit" id="submit" value="submit" disabled></td></tr>
  </table>
</form>

Also the .change() method's a bit better here, to ensure you have the correct state.

Nick Craver
+1 Didn't know that! Does this also work for other `x="x"` attributes like `readonly` etc?
BoltClock
@BoltClock's - Yup, `selected` as well, each of those are booleans in the DOM :)
Nick Craver
@Nick, that's perfect. Thank you. I will check this as the right answer once the time limit is up.
TaraWalsh
@Nick: Will you run into any IE issues with change? I know I've had problems with IE and the change event in the past, so I'm just wondering if it would apply here.
Jeff Rupert
@Jeff - Nope, that's with bubbling, and in < 1.4.2 versions :)
Nick Craver
@Nick: Interesting. I was having an issue in IE8 using 1.4.2 with the `change` event not updating a `select`. Good to know, though. =)
Jeff Rupert