1

I have a a checkbox:

<div class="checkbox">
    <label>
        <?= Html::checkbox('chocolate', false) ?>
        Chocolate
    </label>
</div>

Also I have a span tag:

<span>I like all chocolates.</span>

I want to use the onchange JavaScript function or jQuery (I am beginner using jQuery) to show the span if the user check the checkbox.

First I need to get the value of chocolate. But it is not JavaScript code, it is PHP code: <?= Html::checkbox('chocolate', false) ?>.

1 Answer 1

1

I suggest to add a class to your span. After, you can add a change event handler to your checkbox in order to toggle the display style: from none to block.

In order to add the script to your view, you may add the script itself at the bottom of your view in the script tags:

 <script>
    document.querySelector('.checkbox [type="checkbox"][name="chocolate"]').addEventListener('change', function(e) {
        console.log(this.checked);
        document.querySelector('span.chocoLike').style.display = (this.checked) ? 'block' : 'none';
    })
</script>

document.addEventListener("DOMContentLoaded", function(e) {
    document.querySelector('.checkbox [type="checkbox"][name="chocolate"]').addEventListener('change', function(e) {
        console.log(this.checked);
        document.querySelector('span.chocoLike').style.display = (this.checked) ? 'block' : 'none';
    })
})
.chocoLike {
    display: none;
}
<div class="checkbox">
    <label>
        <input type="checkbox" name="chocolate">
        Chocolate
    </label>
</div>
<span class="chocoLike">I like all chocolates.</span>

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

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.