如果使用JavaScript选中了按钮,则将送货复制到帐单地址

时间:2019-02-09 13:08:50

标签: javascript html

当我单击复选框时,我试图将送货地址复制到帐单上,但是不起作用

这是HTML

<h1>JavaScript Homework</h1>
    <p>Add the JavaScript code needed to enable auto-complete on this form.  Whenever the checkbox is checked, the code should automatically copy the values from Shipping Name and Shipping Zip into the Billing Name and Billing Zip.  If the checkbox is unchecked, the Billing Name and Billing Zip should go blank.</p>

<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>

还有我的JavaScript

function billingFunction(){
 var SN=document.getElementById('shippingName').value;
  var SZ=document.getElementById('shippingZip').value;
  var BN=document.getElementById('billingName').value;
  var BZ=document.getElementById('billingZip').value;
  if (document.getElementById('same').checked==true){ BN=SN;BZ=SZ}
else {BN="";BZ=""}
}

我不知道为什么它不起作用。谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在不对其进行任何操作之前,请勿将其设置为变量。 这将起作用:

var SN = document.getElementById("shippingName");
var SZ = document.getElementById("shippingZip");
var BN = document.getElementById("billingName");
var BZ = document.getElementById("billingZip");

function billingFunction() {
  if (document.getElementById("same").checked == true) {
    BN.value = SN.value;
    BZ.value = SZ.value;
  } else {
    BN.value = "";
    BZ.value = "";
  }
}