Stas Motorny
Stas Motorny

Reputation: 195

.submit is not a function, but i have no names or ids "submit". Why?

I have form with input and button that has type="submit". When i am trying to create a submit event i got an error "submit is not a function".

I was trying to google this problem, but found only one solution, that is to change all names and ids "submit".

html

<form action="" className="testform">
  <input type="text" name="entry.1385083426"/>
  <button type="submit">Send</button>
</form>

js

var forma = document.getElementsByClassName("testform");
forma.submit(function(e){
  e.preventDefault();
  var formData = this;
  console.log(this);
});

Upvotes: 0

Views: 105

Answers (2)

Artyom
Artyom

Reputation: 46

Method "getElementsByClassName" returns HTMLCollection, not HTMLElement. HTMLCollection does not have a "submit" method.

Use method "addEventListener" to set event listener. Also, your js-code must be either inserted after your html-form or executed after triggering DOMContentLoaded event. Otherwise the form will not be found.

<form action="" class="testform">
  <input type="text" name="entry.1385083426"/>
  <button type="submit">Send</button>
</form>
<script>
var forma = document.getElementsByClassName("testform");
forma[0].addEventListener('submit',function(e){
  e.preventDefault();
  var formData = this;
  console.log(this);
});
</sctipt>

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44125

You have a few problems:

  1. Your form element has an invalid className attribute - this should just be class.
  2. getElementsByClassName returns a HTMLCollection - like an array. You want to only access the first one of these, so use getElementsByClassName("testform")[0].
  3. You are attaching your submit event handler the wrong way - either use onsubmit or addEventListener.

Here's the fixed code:

<form action="" class="testform">
  <input type="text" name="entry.1385083426"/>
  <button type="submit">Send</button>
</form>

JavaScript:

var forma = document.getElementsByClassName("testform")[0];
forma.addEventListener("submit", function(e){
  e.preventDefault();
  var formData = this;
  console.log(this);
});

Upvotes: 1

Related Questions