简体   繁体   English

document.querySelector.value 返回值

[英]document.querySelector .value return value

I have a web page with a few radio button selections.我有一个带有几个单选按钮选项的 web 页面。 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?我认为这应该将 hotend 设置为 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.但是当组中没有选择单选按钮时,这似乎会使网页崩溃,因为 function 的 rest 没有运行。 How do I capture this and process the rest of the function?我如何捕获它并处理 function 的 rest?

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.您的代码“崩溃”是因为您试图访问null对象的属性value

Because document.querySelector('input[name="hotend"]:checked') returns null when there's no radio buttons selected.因为document.querySelector('input[name="hotend"]:checked')在没有选择单选按钮时返回null

You're basically doing this when no radio button is selected: null.value .当没有选择单选按钮时,您基本上是在执行此操作: null.value

Try this:尝试这个:

 const hotendElement = document.querySelector('input[name="hotend"]:checked'); const hotend = hotendElement.value?? "No hotend selected";

Also, do not use var .另外,不要使用var Use const and let .使用constlet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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