I have a web page with a few radio button selections. Not all of the radio button options have to be selected. To get the value of each of the Radio Button options I am using this:
var hotend = document.querySelector('input[name="hotend"]:checked').value;
I would think that this should set hotend to null? But it seems like this crashes the webpage when there hasn't been a radio button selected in the group because the rest of function does not run. How do I capture this and process the rest of the function?
Here is the entire code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<h1>parts</h1>
<label for="printer">Choose a part:</label>
<select id="printer" name="printer">
<option value="none">Select Printer</option>
<option value="CR_10">CR-10</option>
</select>
<br />
Choose a hotend:
<div class="flex-container">
<div>
<input type="radio" id="creality_OEM" name="hotend" value="Creality_OEM">
<label for="creality_OEM">Creality OEM</label>
</div>
<div>
<input type="radio" id="micro_swiss" name="hotend" value="Micro_Swiss">
<label for="micro_swiss">Micro Swiss</label>
</div>
</div>
<button class="button" onclick="createParts();" >Generate Parts List</button>
<div id="parts_list">
test
</div>
<div id="test">
something
</div>
<script>
function createParts(){
var partsList="";
var errorList="";
const printer = document.getElementById('printer').value;
let nullTest = document.querySelector('input[name="hotend"]:checked');
const hotend= nullTest.value ?? "";
document.getElementById('parts_list').innerHTML=partsList;
document.getElementById('test').innerHTML="something";
}
</script>
</body>
</html>
Your code "crashes" because you're trying to access the property value on a null˙object.
Because document.querySelector('input[name="hotend"]:checked') returns null when there's no radio buttons selected.
You're basically doing this when no radio button is selected: null.value.
Try this:
const hotendElement = document.querySelector('input[name="hotend"]:checked');
const hotend = hotendElement.value ?? "No hotend selected";
Also, do not use var. Use const and let.