我正在使用JavaScript为表单创建自动完成功能,并且我的HTML文件中的复选框遇到了问题。基本的想法是用户应该能够在表单字段集中填写他们的运输名称和邮政编码,然后如果他们检查"结算信息是否相同?",JS功能将是被称为填写帐单名称和邮政编码的帐单字段集,具有相同的运费值。该复选框可以完成此操作,但我无法取消选中它以清除结算信息。基本上,我无法取消选中我的复选框。我的代码如下:
function billingFunction(){
var billName=document.getElementById("billingName");
var shipName=document.getElementById("shippingName");
var billZip=document.getElementById("billingZip");
var shipZip=document.getElementById("shippingZip");
var same=document.getElementById("same");
if (same.checked=true){
billName.value=shipName.value;
billZip.value=shipZip.value;
}
else{
billName.value="";
billZip.value="";
}
}

<form>
<fieldset>
<legend>Shipping Information</legend>
<label for ="shippingName">Name:</label>
<input type = "text" name = "shipName" id = "shippingName" required><br/>
<label for = "shippingZip">Zip code:</label>
<input type = "text" name = "shipZip" id = "shippingZip" pattern = "[0-9]{5}" required><br/>
</fieldset>
<input type="checkbox" id="same" name="same" onchange= "billingFunction()"/>
<label for = "same">Is the Billing Information the Same?</label>
<fieldset>
<legend>Billing Information</legend>
<label for ="billingName">Name:</label>
<input type = "text" name = "billName" id = "billingName" required><br/>
<label for = "billingZip">Zip code:</label>
<input type = "text" name = "billZip" id = "billingZip" pattern = "[0-9]{5}" required><br/>
</fieldset>
<input type = "submit" value = "Verify"/>
</form>
&#13;
答案 0 :(得分:3)
您的if语句比较未使用正确的相等性检查,而是将checked属性指定为true。更改您的代码:
if (same.checked=true){ //This does assignment
billName.value=shipName.value;
billZip.value=shipZip.value;
}
else{
billName.value="";
billZip.value="";
}
对此:
if (same.checked === true){ //This does equality check
billName.value=shipName.value;
billZip.value=shipZip.value;
}
else{
billName.value="";
billZip.value="";
}
答案 1 :(得分:1)
您正在为same.checked指定值true,因为您已经留下了一个等号。修改:if(same.checked == true)或简单地if(same.checked)