javascript - 为什么已检查的 radio 输入的值可以正确访问,但在 "for"循环内访问时默认为组中的第一个值?

标签 javascript html validation for-loop radio-button

HTML:

<div class="col-md-6 parameter">
    <h3>Property Type</h3><br>
    <input type="radio" value="residential" name="property_type" id="residential-property"><label for="residential-property">Residential</label><br>
    <input type="radio" value="commercial" name="property_type" id="commercial-property"><label for="commercial-property">Commercial</label><br>
</div>

JS:

// Get Property Type
var property_type = document.querySelector('[name=property_type]:checked').value || "";
console.log(property_type);

if (property_type = "residential") {
    hello.innerHTML = "<div class='answer'>" + property_type + "</div>";
}

console.log(property_type) 正确识别选中的单选按钮并返回值,“住宅”或“商业”。但是,当我尝试使用此选定值时,它始终默认为“住宅”。

例如,如果我选择“商业”单选按钮并点击提交,“hello.innerHTML”中的“property_type”值始终默认为“住宅”。奇怪的是,如果我从“if”循环中取出“property_type”值,那么每当我提交时它都会返回正确的值,根据我检查的单选按钮是“住宅”或“商业”。

感谢任何帮助!

最佳答案

相等,

您需要在 if (...) {} 中使用 == 而不是 =

if( property_type == "residential")

关于javascript - 为什么已检查的 radio 输入的值可以正确访问,但在 "for"循环内访问时默认为组中的第一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39819746/

相关文章:

javascript - 提交表单时 props 未通过

html - 修复 Internet Explorer 7 浏览器的水平滚动条

css - 将 div 固定到某个位置(随着窗口大小调整而保持固定)

javascript - AngularJS 指令未按预期更新 View

c# - ModelError 和 ValidationResult 有什么区别?

JavaScript 表单验证功能不起作用

javascript - Jquery比较动态生成的控件的值

javascript - 如何让我的机器人向另一个 channel 发送消息?

javascript - 在 umbraco 7.2.5 中实现标签云和唯一名称验证

javascript - $(window).load 在 Firefox 中不显示图像