Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JQuery, why can't I check a checkbox after removeAttr("checked") is called?

I want to check a checkbox if a certain input field is populated.

The solution below works initially. After I enter input, the checkbox is correctly checked. After the input is deleted, the checkbox is unchecked. But after entering input again, the checkbox does not get checked.

<html>
<head>
    <script src="jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $(":input").blur(function() {
            var val = $(this).val();
            var myclass = $(this).attr("class");

            if (val != null && val.length > 0) {
                $(":checkbox." + myclass).attr("checked", "checked");
            } else {
                $(":checkbox." + myclass).removeAttr("checked");
            }
        });     
    });

    </script>
</head>
<body>
<form action="#" method="POST">
  Name is selected? <input id="isNameSelected" type="checkbox" name="isName" class="name_input"></input><br/>
  Name: <input class="name_input" id="name" type="text" name="Name"></input>  
</form>
</body>
</html>
like image 892
Nate Reed Avatar asked Nov 28 '25 05:11

Nate Reed


1 Answers

Operating on the attribute via .attr() is what's messing you up; I haven't thoroughly investigated but I suspect it has to do with the juggling that jQuery does with attributes like "checked".

You can replace the whole if statement with:

        $(":checkbox." + myclass).prop("checked", !!val);

That'll check or uncheck the checkbox according as whether the text field is non-empty.

Note that because you trigger the handler for any :input element, it'll also trigger when you get a "blur" event from the checkbox.

Also, in my opinion it's a fragile coding practice to rely on the "class" attribute having just one string in it. If you need to group these fields, you can do that either with a container element from which you could use .closest() and .find() to locate companion fields, or else use a data- attribute for what you're currently using the "class".

like image 182
Pointy Avatar answered Nov 29 '25 18:11

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!