M老立
M老立

Reputation: 347

jQuery, unable to check a checkbox

I simply have a checkbox that I want to control the visibility of a dropdown below it by checkbox's status.

<div class="coral-Form-fieldwrapper">
    <label class="coral-Checkbox">
        <input class="coral-Checkbox-input" id="select-all-namespaces" data-init="checkbox" checked data-type="checkbox" data-config-id="selectAll">
            <span class="coral-Checkbox-checkmark"></span>
            <span class="coral-Checkbox-description">Select All</span>
    </label>
</div>
<div class="coral-Form-fieldwrapper">
    <span class="coral-Select some-selection-class" data-init="select" data-config-id="tagNamespaces" name="tagNamespaces">
        <button type="button" class="coral-Select-button coral-MinimalButton">
            <span class="coral-Select-button-text">{{i18n "Select something"}}</span>
        </button>
        <select class="coral-Select-select" multiple="true">
            {{#each configOptions}}
                <option value="{{encodeForHTMLAttr this.id}}">{{this.label}}</option>
            {{/each}}
        </select>
    </span>
</div>

This is the JavaScript that controls it:

var $an = $("#select-all-namespaces");
var $tn = $(".some-selection-class")
if($an.data("default")) { // I broke point into this statement, made sure 'checked' prop set to true 
    $an.prop("checked", true);
    $tn.hide();
} else {
    $an.prop("checked", false);
    $tn.show();
}
$an.on("click", function() {
    if($an.is(":checked")) {
        $tn.hide();
    } else {
        $tn.show();
    } 
});

However, the checkbox loads by default as 'unchecked', after clicking it, the dropdown shows up, but my issue is the checkbox can never be checked, so the dropdown won't disappear. I wonder what's preventing me from setting 'checked' status.

Sigh...Fiddle seems to work well :(

http://jsfiddle.net/9cn2cLrx/

Upvotes: 0

Views: 1093

Answers (1)

mmilleruva
mmilleruva

Reputation: 2178

Here is a jsfiddle that should be working. Two things that I did were add type="checkbox" and add data-default="true" to the #select-all-namespaces element. It wasn't entirely clear what behavior you are going for but you can change the data-default value to change if the checkbox is checked or not by default.

https://jsfiddle.net/vryjpjhp/

Upvotes: 1

Related Questions