html 如果使用JavaScript选中按钮,则复制发货至账单地址

ojsjcaue  于 2023-05-12  发布在  Java
关注(0)|答案(2)|浏览(109)

当我们点击复选框时,我试图将送货地址复制到账单中,但它不起作用
这是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=""}
}

我不知道为什么它不工作。谢谢你的帮助。

ozxc1zmp

ozxc1zmp1#

不要在未对变量执行任何操作的情况下将值设置为变量。这将工作:

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 = "";
  }
}
qxsslcnc

qxsslcnc2#

你可以试试这些

const billingFunction = () => {
    const checkbx = document.getElementById('same')

    if(checkbx.checked){
        const shippingName = document.getElementById('shippingName')
        const shippingZipCode = document.getElementById('shippingZip')
        document.getElementById('billingName')
        document.getElementById('billingZip')
        billingName.value = shippingName.value
        billingZip.value = shippingZip.value
    } else {
        document.getElementById('billingName').value = "";
        document.getElementById('billingZip').value = "";
    }
}

相关问题