0

I have already used addEventListener for other context but in this context, I failed to see why it doesn't not seem to work :

UPDATE : have fixed [0] missing

https://jsfiddle.net/gyy37w7z/2/

<!DOCTYPE html>
<html>
<body>
<table>
<tbody>
<tr>
<td>


<form action="demo_form.asp">
Username: <input type="text" name="usrname" class="myClass"><br>
<input type="submit" value="Submit">
</form>

</td>  
</tr>  
</tbody>
</table>

</body>
</html>

script :

button = document.getElementsByClassName("myClass")[0];
function hello() {alert('hello')};
button.addEventListener("click",hello);
user310291
  • 36,946
  • 82
  • 271
  • 487
  • You tie event listener to input with class `myClass` instead of button – Nikolay Ermakov Feb 01 '16 at 13:32
  • `getElementsByClassName` returns list of all DOM elements having the specified class. To get the first element you can use `getElementsByClassName('myClass')[0]` or you can use `querySelector('.myClass')` – Tushar Feb 01 '16 at 13:33
  • @tushar have fixed still does not work – user310291 Feb 01 '16 at 13:34
  • You're sure you don't just want to hook into the forms submit event, rather than clicking a text input ? – adeneo Feb 01 '16 at 13:36
  • 1
    @user310291, what doesn't "work"? What do you want it to do? When you click on the input it alerts "hello", Do you want it on the submit button instead? – Gavriel Feb 01 '16 at 13:36

3 Answers3

1

Change to this:

button = document.getElementsByClassName("myClass")[0];
function hello() {alert('hello')};
button.addEventListener("click",hello);

getElementsByClassName returns an array so if there's only one then you need index [0] which is the first instance

Here is a fiddle to show working example

StudioTime
  • 22,603
  • 38
  • 120
  • 207
1
button = document.getElementsByClassName("myClass");

returns an array of elements, you want to reach the 1st element add [0].

button = document.getElementsByClassName("myClass")[0];

And you probably mixed the input with the button as well, use:

// get the button by id (I added it)
button = document.getElementById("submit");

function hello() {alert('hello')};
button.addEventListener("click",hello);
<table>
<tbody>
<tr>
<td>
<form action="demo_form.asp">
Username: <input type="text" name="usrname" class="myClass"><br>
<input id="submit" type="submit" value="Submit">
</form>
</td>  
</tr>  
</tbody>
</table>
Gavriel
  • 18,880
  • 12
  • 68
  • 105
1

Just add class="myClass" to button and remove same from text input.

<form action="demo_form.asp">Username: 
      <input type="text" name="usrname"><br>
      <input class="myClass" type="submit" value="Submit">
</form>
Nikolay Ermakov
  • 5,031
  • 2
  • 11
  • 18