cgee cgee - 4 months ago 9
HTML Question

Change input property by clicking on a label

What I need:

If I click on a label I want to add a checked in the input.

When I try it I got two alerts with a true. That isn't correct and in firebug the input field doesn't change.

For a test I want to output the filterguid but the alerts are empty and again there are two alert boxes.

HTML Markup:

<li>
<label>
<input type="checkbox" filterguid="895f7bc2-d609-4b09-97f9-c09f9fc90d1b"> Weiblich
</label>
</li>


jQuery:

$('.targetgroup-frame li label').on('click', function(){
$(this).children().prop('checked', true);
alert($(this).children().prop('filterguid'));
});


Is my jQuery code correct?

Thank you.

Answer

HTML - no changes except adding a id on the input for easy jquery-targeting.

<li>
    <label>
        <input type="checkbox" id="checkbox" filterguid="895f7bc2-d609-4b09-97f9-c09f9fc90d1b"> Weiblich
    </label>
</li>

You don't have to use jquery to change the state of the checkbox since html does that for you.

You can listen for the changes and get the checked state and filterguid with the following script.

$('#checkbox').change(function() {
    console.log($(this).attr('filterguid'))
    console.log(this.checked)
});