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/