猿问

如何在Javascript中获取单选按钮的值?

我创建了一个管理页面,我在其中输入了类似 type='name' 的值,该值将作为单选按钮提交到另一个页面时弹出。但是我从发布单选按钮的页面上的控制台收到错误“无法读取 null 的属性值”。

let answer = document.querySelector('input[name="choice"]:checked').value;


小唯快跑啊
浏览 131回答 2
2回答

尚方宝剑之说

var radios = document.getElementsByName('genderS');for (var i = 0, length = radios.length; i < length; i++) {&nbsp; &nbsp; if (radios[i].checked) {&nbsp; &nbsp; &nbsp; &nbsp; // do whatever you want with the checked radio&nbsp; &nbsp; &nbsp; &nbsp; alert(radios[i].value);&nbsp; &nbsp; &nbsp; &nbsp; // only one radio can be logically checked, don't check the rest&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}<label for="gender">Gender: </label><input type="radio" name="genderS" value="1" checked="checked">Male</input><input type="radio" name="genderS" value="0" >Female</input>

收到一只叮咚

您提供的代码段应该可以工作。它确实假设 HTML 中有输入字段:有name="choice",并且已被检查没有看到 HTML,很难说,但可能会在 HTML 中查找拼写错误。document.getElementById('button').addEventListener('click', () => {&nbsp; const radio = document.querySelector('input[name="choice"]:checked');&nbsp; if (radio) {&nbsp; &nbsp; const answer = radio.value;&nbsp; &nbsp; console.log(`choice ${answer}`);&nbsp; } else {&nbsp; &nbsp; console.log('no choice');&nbsp; }});<label><input type="radio" name="choice" value="1" /> One</label><label><input type="radio" name="choice" value="2" /> Two</label><div>&nbsp; <button id="button">Click</button></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答