1

I am making a checklist. I am adding the checkboxes dynamically via javascript and adding labels for them too.
Now I want when I check a checkbox the background color of the label to change indicating the item has been selected but onClick attribute is not allowed in "label" tag. So I added the text as a child of checkbox but it is not visible but the onclick event is working on checkbox.

var chked = document.createElement("input");
            chked.type = 'checkbox';
            chked.value = data[friendIndex].id;
            chked.id = friendIndex;
            chked.width = '300';
            chked.onclick =  function (){document.getElementById(this.id).style.backgroundColor='#4285f4';};
            var label = document.createElement('label');
            label.htmlFor = friendIndex;
            label.id = friendIndex;
            label.setAttribute('onclick' ,function (){document.getElementById(this.id).style.backgroundColor='#4285f4';});
            label.appendChild(document.createTextNode(data[friendIndex].name));
            chked.appendChild(document.createTextNode(data[friendIndex].name));
            var mybr=document.createElement('br'); 
            chklstTarget.appendChild(chked);
            chklstTarget.appendChild(label);
            chklstTarget.appendChild(mybr);
2
  • rendered html format?? r u covering input with label or bot are sepereate? Commented Jan 30, 2014 at 8:21
  • yes rendered in html<br>i am covering input by label Commented Jan 30, 2014 at 8:23

3 Answers 3

2

Any reason you need to do this via Javascript? You can do this using CSS only.

HTML:

<input type="checkbox" />
<label>Check Me!</label>

CSS:

input[type=checkbox] + label {
    color: black;
}
input[type=checkbox]:checked + label {
    background: red;
}

DEMO HERE

Sign up to request clarification or add additional context in comments.

Comments

0

Use jquery click function to toggle the class

$("input[type=checkbox]").change(function() {
        $(this).parent().toggleClass("checked");
    });

DEMO

Comments

0

How about append CheckBox to Label.
Then you can get CheckBox's onClick event from click ChkeckBox and Label area both.
And change label's color.

example)

label.appendChild( chked );
label.appendChild( textToDisplay );
chklstTarget.appendChild( label );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.