Search code examples
htmlformsradio-button

"Checked" attribute not working after reloading page


I have some HTML code that I am using for a website that looks like this: (with some changed variables)

<div class="radio">
    <label>
    <input type="radio" name="radio2" class="radio2" value="YES">
    YES 
    </label>
</div>
    <div class="radio">
    <label>
    <input type="radio" name="radio2" class="radio2" value="NO" checked="checked">
    NO
    </label>
</div>

This works perfectly fine and "No" is automatically checked when I first load the page, but when I check yes and then reload again, the "yes" option is automatically checked rather than the "no" one. This is a problem because upon checking yes, I display more information and the default should be "no" and display no extra information. I have tried:

    <input type="radio" name="radio2" class="radio2" value="NO" checked="checked">

and

    <input type="radio" name="radio2" class="radio2" value="NO" checked="true">

and

    <input type="radio" name="radio2" class="radio2" value="NO" checked>

and

<input type="radio" name="radio2" class="radio2" value="YES" checked="false">    
<input type="radio" name="radio2" class="radio2" value="NO" checked="true">

but whenever I check yes, the next time I load the page "yes" is checked again. I am using firefox, and using private browsing does not help.


Solution

  • You can try to use js, here is the fiddle

    HTML:

    <form>
        <div class="radio">
            <label>
                <input id="yes" type="radio" name="radio2" class="radio2" value="YES" checked="checked">
                YES 
                </label>
        </div>
        <div class="radio">
            <label>
                <input id="no" type="radio" name="radio2" class="radio2" value="NO">
                NO
                </label>
        </div>
        <input type="submit">
    </form>
    

    JS:

    $(document).ready(function() {
      $('#no').prop('checked', 'checked');
    });