Jquery checkbox inside div checked one at time

帅比萌擦擦* 提交于 2019-12-01 22:12:46

问题


So i have a div thats auto generated and inside are 3 check boxes with different id's & names and by default none of them are checked!! If one happens to get checked then i need the other two unchecked!!

So only one can be checked at a time ...

So all unchecked or only one checked!

<div class="configoptions">
    <table class="configtable" cellpadding="0" cellspacing="0" width="100%">
        <tbody>
            <tr>
                <td class="fieldlabel">Include:</td>
                <td class="fieldarea">
                    <label><input name="configoption[10]" id="co30" value="1" onclick="recalc()" type="checkbox">green</label>
                </td>
            </tr>
            <tr>
                <td class="fieldlabel">Include:</td>
                <td class="fieldarea">
                    <label><input name="configoption[9]" id="co27" value="1" onclick="recalc()" type="checkbox">blue</label>
                </td>
            </tr>
            <tr>
                <td class="fieldlabel">Include:</td>
                <td class="fieldarea">
                    <label><input name="configoption[11]" id="co31" value="1" onclick="recalc()" type="checkbox">white</label>
                </td>
            </tr>
        </tbody>
    </table>
</div>

Here is what i used to uncheck all divs on page ready.. since initially i need them unchecked.. that works great... now i need to make it so only one is check at a time if it is checked! Can someone gimme a hand,? Thx in advance!

$(document).ready(function() {
    $('input[type=checkbox]').each(function() {
        this.checked = false;
    });
});

回答1:


Use the prop function to change the checked property of checkbox and radio buttons

$(function(){
    $('input:checkbox').prop('checked', false)
    $('input:checkbox').click(function(){
        if($(this).is(':checked')){
            $('input:checkbox').not(this).prop('checked', false);        
        }
    });
})

Demo: Fiddle




回答2:


I had a similar issue and solved it like so (using part of Arun P Johny's answer - I wanted to share for those of you who might come across this as well.)

(function($checkbox,options){                               
            $($checkbox).on('change', function() {                  
                $("input[type='checkbox']").not(this).prop('checked', false);               
            });             
        });


来源:https://stackoverflow.com/questions/15356300/jquery-checkbox-inside-div-checked-one-at-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!