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

MichaelHasfel picture MichaelHasfel · Mar 10, 2014 · Viewed 14.2k times · Source

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.

Answer

Danielito picture Danielito · Mar 10, 2014

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.