Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - If no radio buttons are selected, check the first one

I'm a beginner in JavaScript. I have several radio buttons on my dynamic page and I want to create a script to make the following:

HTML:

    <input type="radio" id="elemainfoto">
    <input type="radio" id="elemainfoto">
    <input type="radio" id="elemainfoto">

JavaScript:

    var radio = '#elemainfoto',
    if(radd.value == 0) {
        radd.checked the first radio element,
    } else {
        keep the way it is,
    }

If none of the radio elements are marked, mark the first compulsory.

like image 335
MichaelHasfel Avatar asked Feb 14 '23 13:02

MichaelHasfel


2 Answers

I your expectation is that the first item get selected by default, then you should use HTML and not javascript for that and please note that you should not use two HTML elements with the same id in your case you should either replace by a class and/or add unique Ids for elements.

<input type="radio" class="elemainfoto" id="item1" checked>
<input type="radio" class="elemainfoto" id="item2">
<input type="radio" class="elemainfoto" id="item3>

Updated the answer based on RobG comment.

like image 149
Danielito Avatar answered Feb 16 '23 03:02

Danielito


Something like this in pure JS (I changed ids to classes id should be unique):

var radio = document.querySelectorAll('.elemainfoto'),
    checked = false;

for (var i = 0; i < radio.length; i++) {
    if (radio[i].checked) {
        checked = true;
        break;
    }
}

if (!checked) {
    radio[0].checked = true;
}
else {
    alert('something is checked')
}

A little shorter with jQuery:

var $radio = $('.elemainfoto');

if (!$radio.filter(':checked').length) {
    $radio[0].checked = true;
}
else {
    alert('something is checked')
}
like image 20
dfsq Avatar answered Feb 16 '23 01:02

dfsq