CharlieT
CharlieT

Reputation: 414

Javascript check if one radio button is selected

I am trying to check that a user select at least one radio button. When clicking on the checkbox called mallname, I need to check if one of the payment radioboxes were checked.

Here is my HTML for payment (I need to check if one of these two are checked)

<fieldset>
<legend>Payment method</legend>
<div class='container'>
<label for='payment' >Please select payment method.:</label>
<p>
<label for='payment' >Once off (Full Payment):</label> 
<input type='radio' name='payment' id='paymentoo' onClick="SetHTML2('once')" value="Once off (Full Payment)" required <?php echo($isOnceoffFullPayment?'checked="checked"':''); ?> maxlength="50" />
<span id='register_payment_errorloc' class='error'></span>
<label for='payment' >Monthly Debit:</label>
<input type='radio' name='payment' id='paymentmd' onClick="SetHTML2('montly')" value="Monthly Debit" required <?php echo($isMonthlyDebit?'checked="checked"':''); ?> maxlength="50" />
<span id='register_payment_errorloc' class='error'></span>
<br>
</div>
</fieldset>

HTML for checkbox

<td width='400'><label for='contract' >$malls</label></td><td width='100'><input type='checkbox' name='mallname[]' id='mallname' value='$malls' onclick = 'checkpayment(); addemupfull(); addemupfulldebit();'/></td>

Here is my java

<script type="text/javascript">
function checkpayment(){
var payoo = document.getElementById("paymentoo");
var paymd = document.getElementById("paymentmd");
if(!(payoo || paymd).checked){
var malchecks = document.getElementById("mallname");
malchecks.checked = false;
alert("Please select a payment method first");
}
}
</script>

It works when 'paymentoo' is selected, but when 'paymentmd' is selected I still get the alert "Please select a payment method first"

Upvotes: 2

Views: 1522

Answers (2)

somethinghere
somethinghere

Reputation: 17340

Your issue is with this statement (payoo || paymd) - because payoo will always exist, all you are checking is whether payoo is checked. What you need is:

if(!(payoo.checked || paymd.checked)))

Or, an even faster way could be:

if(document.querySelectorAll('#paymentoo:checked, #paymentmd:checked').length)

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

!(payoo || paymd).checked will only check whether payoo is checked as the logical OR operator will return the first truthy value - since payoo is a dom element it will always return that

You need to check

if (!payoo.checked && !paymd.checked) {// if (!(payoo.checked || paymd.checked)) {
    var malchecks = document.getElementById("mallname");
    malchecks.checked = false;
    alert("Please select a payment method first");
}

Upvotes: 4

Related Questions