Check a checkbox by clicking the parent container?

前端 未结 3 1573
刺人心
刺人心 2021-01-27 09:03

Instead of having to click the little specific checkbox area, id like to check the checkbox by clicking the parent container, here is an example fiddle. Instead of adding the co

相关标签:
3条回答
  • 2021-01-27 09:51

    you can use <label> tag

    http://www.w3schools.com/tags/tag_label.asp

    0 讨论(0)
  • 2021-01-27 09:51

    http://jsfiddle.net/CVjCr/1/

    Added $(this).find('input').prop('checked', true);

    0 讨论(0)
  • 2021-01-27 10:00

    You can do it like this:

    Original without changing to <label>s:

    $('li').click(function(){
        var el = $(this).toggleClass('seuss');
        el.find('input[type=checkbox]').prop('checked', el.hasClass('seuess'));
    });
    

    Updated using <label>s:

    HTML:

    <li class="option table selected">
        <label for="personalization_result_memory_0">
            <div class="cell" id="left">
                <div class="fontawesome-menu"></div>
            </div>
            <div class="cell" id="center">
                <div class="option-text">I like green eggs</div>
            </div>
            <div class="cell" id="right">
                <div class="option-checkbox">
                    <div class="check"></div>
                    <input name="personalization_result[memory_0]" type="hidden" value="0">
                    <input id="personalization_result_memory_0" name="personalization_result[memory_0]" type="checkbox" value="1">
                </div>
            </div>
        </label>
    </li>
    

    Javascript:

    $('input[type=checkbox]').change(function(){
        var el = $(this).closest('li').toggleClass('seuss');
    });
    

    Note, even when you wrap the input in the <label>, you should use the for attribute.

    0 讨论(0)
提交回复
热议问题