简体   繁体   中英

JavaScript: How to assign a default value if none of the radio buttons are selected

In an HTML form, a radio button named color may or may not exist. I'd like to check if this radio button doesn't exist or if it exists none of the radio buttons is selected and if so, assign a default value:

if (document.getElementsByName("color") === undefined){
      color= "red";
   }else{
      color = document.querySelector('input[name="color"]:checked').value;
}

But the code always goes to the 'else' whether a radio button exist or not, is selected or not, and then complains "Uncaught TypeError: Cannot read property 'value' of null."

What am I doing wrong?

getElementsByName returns an array and a blank one if no records

if (document.getElementsByName("color").length == 0){
    color= "red";
} else {
    color = document.querySelector('input[name="color"]:checked').value;
}

You don't need to mix getElementsByName with querySelector :

Snippet when checkbox exists

 var color = 'red'; var check = document.querySelector('input[name="color"]:checked'); if (check) color = check.value; console.log(color); 
 <input type="checkbox" name="color" value="Hello!" checked> 

Snippet when checkbox doesn't exist

 var color = 'red'; var check = document.querySelector('input[name="color"]:checked'); if (check) color = check.value; console.log(color); 

Snippet when dropdown exist

 var color = 'red'; var selected = document.querySelector('select[name="color"] option:checked'); if (selected) color = selected.value; console.log(color); 
 <select name="color"> <option value='one'>One<option> <option selected value='two'>Two<option> </select> 

Resource

getElementsByName function returns a NodeList element, even if it's empty!

You can check length of result if (document.getElementbyName('color').length === 0)

Working demo

Because you are using querySelector with :checked , then it only selects checked checkboxes with the name "color". If no checkboxes are checked, then it will return null . And because null has no key value , you get an error. Try

if (document.querySelector('input[name="color"]:checked') === null){
  color= "red";
}else{
  color = document.querySelector('input[name="color"]:checked').value;
}

To add to the existing answers, DOM queries are expensive! So try and re-use one query rather than wasting time executing two redundant queries:

var color = (
  document.querySelector('input[name="color"]:checked') || { value: 'red' }
).value;

document.querySelector() will return null if no such element exists, so the || operator will either short-circuit if there is an element, or return { value: 'red' } if there isn't, then access the value property of whichever object is chosen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM