Search code examples
javascriptangularjsangularjs-directivescopeangularjs-scope

Get the child input tag for the current checkbox clicked


I am trying to get the child input tag for the current checkbox that is clicked and add checked to it through my directive. I have the directive setup correctly but I am getting undefined when I try to get elem[1]

HTML:

<div class="checkbox">
    <input id="checkbox1" type="checkbox" checked ng-model="checkboxoption.value1">
    <span class="custom"></span>
    <label for="checkbox1">Checkbox 1</label>
</div>

JS:

.directive('checkbox', [function() {
    return {
        restrict: 'C',
        scope: {},
        link: function(scope, elem, attr) {
            elem.bind('click', function(evt) {
                var currentCheckbox = elem[1];
                console.log(elem[1]);
                elem.prop('checked');
            });
        }
    };
}])

Solution

  • elem is a jQuery or jqLite object. The subscript lets you index into the collection of elements matched by a selector. So for example, in jQuery,

    $("span")[1]
    

    gets the second span on the page. On the other hand,

    $("body")[1]
    

    should return undefined because there should only be one body.

    There is only one element (the <div class="checkbox">) in elem. To get its second child, you can do this:

    elem.children()[1]
    

    But you probably want its first child, since the checkbox comes first in your HTML:

    elem.children()[0]
    

    Another approach is:

    elem.find("input")[0]
    

    That may be better since it won't break if you change the order of the elements in your HTML.

    Both of these will get you a plain DOM object. Once you have the checkbox element, you can set its checked attribute like this:

    elem.children()[0].checked = true;
    // or
    elem.find("input")[0].checked = true;
    

    By the way, you should probably remove the id element from your checkbox, because if you use this directive more than once, the ID will be duplicated.