简体   繁体   中英

Check if a radio button is selected

I don't understand why this is not working

I have a radio button Yes or No. Yes uses "id=statut1"

<label class="radio inline">
    <input type="radio" name="statut" id="statut1" value="1"<?php if($statut=='1') echo ' checked="checked"'; ?>> Actif
</label>

At some point, I would like to know if the Yes radio button is selected or not. I used this

console.log($('#statut1'));
if($('#statut1').is('checked')){
    console.log("inside");
}

When I look into the log, whatever the checked value is (true or false) I never go inside the condition. I can't understand why this is not working. I'm doing the same thing with a checkbox and I have no issue.

Looks like is('checked") doesn't work for radio button...but still I found many subjects here saying it's working.

Thanks for help.

I think you missed a colon. Use like this:

$('#statut1').is(':checked')

Try this:

Put colons inside (:)

$('#' + id).is(":checked")

Here are two solutions:

Using onchange event you can trigger function.

Vanilla JS:


 function myFunction(e) { console.log(e.target.checked); } 
 <label class="radio inline"> <input type="radio" name="statut" id="statut1" value="1" onchange="myFunction(event);"> Actif </label> 


jQuery:


 $('#statut1').on('change', e => { console.log(e.target.checked); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class="radio inline"> <input type="radio" name="statut" id="statut1" value="1"> Actif </label> 

OP's Solution:
$('#statut1').is(':checked')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM