Search code examples
htmljqueryradio-buttonchecked

Allowing one radio button checked when radio inputs have different names


I'm trying to figure out how to only allow one of two radio buttons to be checked in a form where the two radio buttons don't share the same name. I've been experimenting for hours now, but can't figure it out. Here is what I have currently:

$("#theForm").click(function(){
    //alert('You clicked radio!');
    if($('input:radio:checked')){
        $('input:radio:checked').prop("checked", false);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="theForm">
    <form class="type">
        <input type="radio" id="topic" name="topic" value="on" checked>
        <input type="radio" id="all" name="all" value="on">
    </form>
</div>

Here's a Fiddle: https://jsfiddle.net/Codewalker/reh0mzs3/1/


Solution

  • the click function will give you an event. you can target the event.target.name to see which radio button was clicked on and then do a simple if statement to uncheck the other radio button

    $("#theForm").click(function(){           
        if(event.target.name == 'topic'){          
            $('#all').prop("checked", false);
        }else{
           $('#topic').prop("checked", false);
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="theForm">
        <form class="type">
            <input type="radio" id="topic" name="topic" value="on" checked>
            <input type="radio" id="all" name="all" value="on">
        </form>
    </div>