无法取消选中复选框 (HTML)

Mat*_*sso 2 html javascript checkbox

我正在使用 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="";
  }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Rya*_*son 5

您的 if 语句比较没有使用正确的相等性检查,而是将检查的属性分配为 true。更改您的代码:

if (same.checked=true){ //This does assignment
   billName.value=shipName.value;
   billZip.value=shipZip.value;
}
else{
   billName.value="";
   billZip.value="";
}
Run Code Online (Sandbox Code Playgroud)

对此:

if (same.checked === true){ //This does equality check
   billName.value=shipName.value;
   billZip.value=shipZip.value;
}
else{
   billName.value="";
   billZip.value="";
}
Run Code Online (Sandbox Code Playgroud)