1

I'm going through a book on Jquery, came across an exercise, but it's not working, checked some related problems on stackoverflow and crosschecked with what I've done so far, it's almost the same but mine is not working, can someone please profer a solution? Here is the code:

<form action="#">
Billing Address same as Shipping Address:
<input type="checkbox" name="billingAddress" id="billingAddress" />
<br />
<br />
Street Address:
<input class="baddr" type="text" name="street" id="street" />
<br />
<br />
City:
<input class="baddr" type="text" name="city" id="city" />
</form>

<script type="text/jscript">
$(document).ready(function() {
    $("#billingAddress").click(function() {
        if ($("#billingAddress").attr("checked") == true) {
            alert("Id billingAddress is checked!");
            $(".baddr").val("");
            $(".baddr").attr('disabled', 'disabled');   
        } else if ($("#billingAddress").attr("checked") == undefined) {
            $(".baddr").removeAttr("disabled"); 
        }
    });
});
</script>
Zia
  • 307
  • 4
  • 11
  • Someone else gave an answer, but as a point of style, if you have something like `if(b == true)` where `b` is a boolean, please reduce this to `if(b)`. – rafalio May 20 '14 at 22:55
  • 1
    This seems like a good opportunity to learn about the difference between HTML attributes and DOM properties: http://stackoverflow.com/q/6003819/218196, http://stackoverflow.com/q/7588846/218196, http://stackoverflow.com/q/5874652/218196, http://stackoverflow.com/q/10280250/218196 – Felix Kling May 20 '14 at 23:02

1 Answers1

0

Working demo: there are many ways one of which is : http://jsfiddle.net/J9vWu/

Another version with use of this and chaining few thigns: http://jsfiddle.net/z9xjB/ or http://jsfiddle.net/NzEjK/

code

$(document).ready(function () {
    $("#billingAddress").click(function () {
        if ($("#billingAddress").prop("checked")) {
            alert("Id billingAddress is checked!");
            $(".baddr").val("");
            $(".baddr").prop('disabled', 'disabled');
        } else if ($("#billingAddress").prop("checked") == undefined) {
            $(".baddr").removeAttr("disabled");
        }
    });
});

Or

$(document).ready(function () {
    $("#billingAddress").click(function () {
        if ($(this).prop("checked")) {
            alert("Id billingAddress is checked!");
            $(".baddr").val("").prop('disabled', 'disabled');;
        } else if ($(this).prop("checked") == undefined) {
            $(".baddr").removeAttr("disabled");
        }
    });
});
Tats_innit
  • 33,991
  • 10
  • 71
  • 77