4

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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
MichaelHasfel
  • 41
  • 1
  • 1
  • 7

7 Answers7

4

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.

Danielito
  • 169
  • 4
  • The radio buttons are dynamically generated, so I can not do that. – MichaelHasfel Mar 10 '14 at 13:00
  • 1
    The checked attribute is a [boolean attribute](http://www.w3.org/html/wg/drafts/html/master/infrastructure.html#boolean-attribute), it does not have any value. Where one is required (which is only for XHTML, which is not used on the web) the value must be the same as the attribute name, i.e. `checked="checked"`. – RobG Mar 10 '14 at 13:02
  • 1
    @user2697222—of course you can, just set the *checked* attribute or *defaultChecked* property once the buttons are created. – RobG Mar 10 '14 at 13:03
  • is the issue that when dynamically generated a _different_ option might be selected (perhaps based on database values?) and so you need to allow for that and not just set the first as default ? – Michael Durrant Mar 10 '14 at 13:06
3

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')
}
War10ck
  • 12,387
  • 7
  • 41
  • 54
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Filter seems like it would be pretty inefficient in this case. Couldn't you just do `if(!$('.RB:checked').length)`... – War10ck Mar 10 '14 at 13:05
  • @War10ck I could but it would be event less efficient because inside of `if` you need to reselect radio collection again. – dfsq Mar 10 '14 at 13:09
  • Ah, I see what you're doing now. That's clever. I've never used that before. Learn something new everyday. Thanks buddy. :) – War10ck Mar 10 '14 at 13:10
0

using 'id' attribute in html with the same value more than once is invalid, you should use "name" for an input.

HTML:

<input type="radio" name="elementinfoto" value="1" />
<input type="radio" name="elementinfoto" value="2" />
<input type="radio" name="elementinfoto" value="3" />

JavaScript:

 var radio = document.getElementsByName('elementinfoto'); // get all radio buttons
 var isChecked = 0; // default is 0 
 for(var i=0; i<radio.length;i++) { // go over all the radio buttons with name 'elementinfoto'
   if(radio[i].checked) isChecked = 1; // if one of them is checked - tell me
 }

 if(isChecked == 0) // if the default value stayed the same, check the first radio button
   radio[0].checked = "checked";

example: http://jsfiddle.net/yxm4N/2/

Jentel
  • 148
  • 2
  • 17
0

A radio button group is formed by giving radio buttons the same name. An ID is optional and usually not necessary. If an ID is provided, each should have a different value. And the buttons should have a value so that there's a point to their existence.

To have one button selected by default, simply set the chosen button's checked attribute:

<form id="foo">
  <input type="radio" name="elemainfoto" valu="0" checked>0<br>
  <input type="radio" name="elemainfoto" valu="1">1<br>
  <input type="radio" name="elemainfoto" valu="2">2<br>
  <input type="reset">
</form>

Now if no other button is selected, or the form is reset, one button will be selected. Note that if you do not set a button as the default selected, then once a user checks a button, the only way to deselect it is to select a different radio button in the same group, or use a reset button (if provided).

If you want to set the default checked button in script, there are a couple of options. One is:

var buttons = document.getElementsByName('elemainfoto');
buttons[0].defaultChecked = true;

If you really want to check if one is selected, add a button like the following to the form:

  <input type="button" value="Check buttons" onclick="checkButtons(this);">

Then the checkButtons function can be:

function checkButtons(el) {
  var buttons;
  var form = el && el.form;

  if (form) {
    buttons = form.elemainfoto;

    for (var i=0, iLen=buttons.length; i<iLen; i++) {

      // If a button is checked, return its value
      if (buttons[i].checked) {
        return buttons[i].value;
      }
    }
  }
  // Otherwise, try to check the first one and return undefined
  buttons && buttons[0].checked;
}
RobG
  • 142,382
  • 31
  • 172
  • 209
0

you need to know how to use radio element. Id is unique in html page. you should assign same name for each radio element.

<input type="radio" name="elemainfoto" id="first" value="1" />
element 1
<input type="radio" name="elemainfoto" id="second" value="2" />
element 2
<input type="radio" name="elemainfotor" id="thrid" value="3" /> 
element 3

if you want to check the first radio button as default, set it in input tag attribute.

<input type="radio" name="elemainfoto" id="first" value="1" checked="true"/>
    element 1

or you can do it with javascript also,

$("input:radio[name=elemainfoto]:first").attr('checked', true);

you can perform action for each radio button click, to know which item is checked

$(function(){
  $('input[type="radio"]').click(function(){
    if ($(this).is(':checked'))
    {
      alert($(this).val());
    }
  });
});

if you want to perform a separate action for each radio button, try this below code

$(function () {
    $('input[type="radio"]').click(function () {
        if ($(this).is(':checked')) {
            if ($(this).val() == '1') alert('first radio element is checked');
            if ($(this).val() == '2') alert('second radio element is checked');
            if ($(this).val() == '3') alert('third radio element is checked');
        }
    });
});

SEE THIS FIDDLE DEMO

CJ Ramki
  • 2,620
  • 3
  • 25
  • 47
0

Instead of selecting the first one, I prefered to use null

const radio = document.querySelectorAll('.timescale');

let timescale;

if (radio.checked) {
  timescale = $('input[name=timescale_radio_buttons]:checked').val()

} else timescale = null;
Spinstaz
  • 287
  • 6
  • 12
0

You can write it like this with less code

HTML

<input type="radio" name="elementinfoto" value="1" />
<input type="radio" name="elementinfoto" value="2" />
<input type="radio" name="elementinfoto" value="3" />

JavaScript

const fields = document.getElementsByName('elementinfoto');
const value = fields.filter(el => el.checked).shift()?.value || null;

if(!value) {
   fields.shift().checked = true;
}

You can replace the function shift() by [0] to get the first element if you prefer

King Julian
  • 101
  • 1
  • 3