user4756836 user4756836 - 1 year ago 65
Javascript Question

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

to it through my directive. I have the directive setup correctly but I am getting
when I try to get


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


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

Answer Source

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,


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


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:


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


Another approach is:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download