最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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 pulsory.

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 pulsory.

Share Improve this question edited Jul 1, 2022 at 20:46 Jonas 129k101 gold badges327 silver badges405 bronze badges asked Mar 10, 2014 at 12:39 MichaelHasfelMichaelHasfel 511 gold badge1 silver badge8 bronze badges 6
  • 2 document.querySelectorAll('[type="radio"]')[0].checked = true? Ow.. and you can't have duplicate IDs, so your HTML is invalid. – putvande Commented Mar 10, 2014 at 12:41
  • A valid HTML page cannot have duplicate IDs. This code would not work . Change ID to class, and change the pseudocode to actual syntax. You should arrive (quite close) to your solution – karthikr Commented Mar 10, 2014 at 12:41
  • Do you want a default kind of behaviour? – Amit Joki Commented Mar 10, 2014 at 12:42
  • Yes, Amit Joki. Jquery is cool! – MichaelHasfel Commented Mar 10, 2014 at 12:44
  • 1 Simply set the first as the default selected, no script required. – RobG Commented Mar 10, 2014 at 12:46
 |  Show 1 more ment

7 Answers 7

Reset to default 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 ment.

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')
}

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/yxm4N/2/

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;
}

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

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;

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

发布评论

评论列表(0)

  1. 暂无评论