TransWikia.com

Как включить автозаполнение в форме с помощью JS?

Stack Overflow на русском Asked by Ezi S on February 20, 2021

Мне нужно добавить код JavaScript, чтобы включить автозаполнение в моей форме.

Когда флажок установлен, код должен автоматически копировать значения из shipping Name и shipping ZIP в Billing Name и Billing Zip . Если флажок снят, поля Billing Name и Billing Zip должны идти пустыми.

Почему моя функция JS не работает?

Внизу мои JS и HTML коды:

function billingFunction () {
  if (document.getElementById('same').checked) {
    var shipinfo = document.getElementById('shippingName','shippingZip').value;
    var billinfo = document.getElementById('billingName','billingZip').value;
    shipinfo = billinfo;
  } else {
    document.getElementById('billingName','billingZip').value = '';
  }   
<h1>JavaScript</h1>
    <p> Whenever the checkbox is checked...</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>

One Answer

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

function billingFunction () {
  if (document.getElementById('same').checked) {
    document.getElementById('billingName').value = document.getElementById('shippingName').value;
    document.getElementById('billingZip').value = document.getElementById('shippingZip').value;
  } else {
    document.getElementById('billingName').value = '';
    document.getElementById('billingZip').value = '';
  }   
}

function billingFunction () {
  let checked = document.getElementById('same').checked;
  document.getElementById('billingName').value = checked? document.getElementById('shippingName').value : '';
  document.getElementById('billingZip').value  = checked? document.getElementById('shippingZip').value  : '';
}

Correct answer by Igor on February 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP