0
<script type="text/javascript">
$(document).ready(function(){
    $("input[name='trim']").click(function (event) {
        if ($(this).val() == "deluxe") {
            $("input[name='option']").attr("checked", true);
        } else if ($(this).val() == "plain") {
            $("input[name='option']").attr("checked", false);
        }
    });
    $("input[name='option']").click(function(event){
        $("#custom").attr("checked","checked");
    });
});
</script>

This is radio and click button problem. First I click deluxe button, check button works fine. Then I click plain button it works fine too. Then I re-click deluxe button, check button won't working. Then I try to test out custom button. It not working either after I click plain button. Does anyone know whats going on? By the way plain works fine from beginning.

Kerry Jones
  • 21,806
  • 12
  • 62
  • 89

2 Answers2

0

You should use jQuery prop() instead of attr(). attr() is buggy.

David W Lee
  • 169
  • 3
  • 1
    Your answer is correct, but the "explanation" that .attr() is buggy is not. The issue isn't one of being buggy, it's of using the right jQ method based on the need. Prior to jQ 1.6, there was no .prop() so .attr() was used for all use cases; with the addition of .prop(), it's specifically for use cases like the OP where you need to get/set an element's Property value vs .attr(), which is for getting/setting a DOM attribute value. They're different, and both functions exist now for that reason. Ref: http://stackoverflow.com/a/16051519/3617262 – Stevangelista Jun 11 '14 at 00:59
  • Thanks for the clarification, Stevangelista. You are right that attr() has its use but it's not what most people expect. In practice, it's better to use prop() about 99% of times. – David W Lee Jun 11 '14 at 01:43
0

Use the following code which is a great jQuery extension. It will accept 1,0,'1','0',true,false, and unidentified. To see in action see my fiddle I posted your usage as well.

(function( $ ) {

  $.fn.checked = function(value) {

    if(value === true || value === false) {
        // Set the value of the checkbox
        $(this).each(function(){ this.checked = value; });
    } else if(value === undefined || value === 'toggle') {
        // Toggle the checkbox
        $(this).each(function(){ this.checked = !this.checked; });
    } else if(value === 1 || value === '1') {
        $(this).each(function(){ this.checked = true; });
    } else if(value === 0 || value === '0') {
        $(this).each(function(){ this.checked = false; });
    }
    return this;
  };

})( jQuery );

Your usage would be like so:

$("input[name='trim']").click(function (event) {
    if ($(this).val() == "deluxe") {
        $("input[name='option']").checked(1);
    } else if ($(this).val() == "plain") {
        $("input[name='option']").checked(0);
    }
});
$("input[name='option']").click(function(event){
    $("#custom").checked(1);
});
Joe Johnston
  • 2,794
  • 2
  • 31
  • 54