0

When the button is nested in a form:

    <div>
        <form action="/">
            <h1>Form</h1>
            <div>
                <input type="text" name="name" id="nameField" placeholder="Full name">
                <input type="number" name="Phone" id="phoneField" placeholder="Phone number">
                <input type="text" name="name" id="itemField" placeholder="item">
                <input type="date" name="name" id="dateField" placeholder="Date">
            </div>
            <button class="button" id="saveButton">Save</button>
        </form>
    </div>

<script src="./index.js"></script>

it will always return null if I am trying to click the button unless I filled in all textfields in this form.

//index.js

const nameTextField = document.querySelector("#nameField");
const phoneTextField = document.querySelector("#phoneField");
const itemTextField = document.querySelector("#itemField");
const dateTextField = document.querySelector("#dateField");
const saveBt = document.querySelector("#saveButton");

saveBt.addEventListener("click", function () {
  const name = nameTextField.value;
  const phone = phoneTextField.value;
  const item = itemTextField.value;
  const date = dateTextField.value;
});


According to Document:

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

Why it is unable to locate the button here?

Stone
  • 29
  • 2
  • 12

0 Answers0