Reputation: 195
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
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
Reputation: 44125
You have a few problems:
form
element has an invalid className
attribute - this should just be class
.getElementsByClassName
returns a HTMLCollection
- like an array. You want to only access the first one of these, so use getElementsByClassName("testform")[0]
.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