2

JavaScript

function billingFunction() {
 if(document.getElementById('same').checked) {
  document.getElementById('billingName').setAttribute('value', shippingName.value);
 }
}

html

<html>

<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<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>
        <script src="autocomplete.js"></script>
</body>     
</html> 

I just come across this example. Could you help me understand why we have to get the element with "same" id with getElementById, whereas shippingName.value is working as is (without getElementById). That shippingName is not a global variable.

The function works. At least in Chrome and Firefox.

The whole example. http://codepen.io/Kifsif/pen/EyvLXq

Michael
  • 4,273
  • 3
  • 40
  • 69
  • 2
    If browsers do not fine a variable they look for elements with that id. It is a bad practice to do this. – epascarello Jul 07 '16 at 18:54
  • Agreed with above. This is a shortcut to write less code but is a bad practice. – Alan Thomas Jul 07 '16 at 18:57
  • Could you a bit broaden your idea a bit. This is not documented in ECMAScript standards (5th or later)? What browsers do support such finding, and which don't? – Michael Jul 07 '16 at 18:58
  • 1
    `getElementById` isn't documented in the ECMAScript spec either. It's a DOM thing not a JS thing. – Quentin Jul 07 '16 at 18:59

0 Answers0