-1

A simple form to submit search result

<form>

    <label for="searchTerm">Search Term</label>
    <input type="text" id="searchTerm" name="searchTerm">
    <button type="submit">Search</button>

</form>

in main.js

const form = document.querySelector("form");
const input = document.querySelector("input");
//adding listener to form 
form.addEventListener("submit", formSubmitted);

I am getting two errors ?

Uncaught TypeError: Cannot read property 'addEventListener' of null

Uncaught SyntaxError: Identifier 'form' has already been declared

Sanjay
  • 665
  • 9
  • 20
  • please tell us how did you arrange the code in html? – Kai Jun 13 '18 at 07:48
  • got my silly error @kai thanks for early response – Sanjay Jun 13 '18 at 07:51
  • First issue might be because you are capturing form before the dom is ready. Second one because you already have a variable/constant declared. With the code you provided there is nothing wrong, we need more context – A. Llorente Jun 13 '18 at 07:52

2 Answers2

0

With document.querySelector() it is best to use an element id #someId or a class specifier .someClass, or even a combination of both. See MDN Reference.

As for why it complains about form: it apparantly is defined already elsewhere, just pick a more unique name, or wrap your code in a function and then call that function.

const form = document.querySelector("#theForm");
console.log("form: " + form);

const input = document.querySelector("#searchTerm");
form.addEventListener("submit", formSubmitted);

function formSubmitted() {
  //...
}
<form id="theForm">
  <label for="searchTerm">Search Term</label>
  <input type="text" id="searchTerm" name="searchTerm">
  <button type="submit">Search</button>
</form>
Peter B
  • 18,964
  • 5
  • 26
  • 60
0

Silly mistake : i had imported same main file twice in same file

<script src="main.js"></script>
Sanjay
  • 665
  • 9
  • 20