WeVie
WeVie

Reputation: 598

How to retrieve submit button with getElementsByTagName

I would like to get the a submit button using getElementsByTagName but I must be doing something wrong.

 <p id="ptag">Want to find out if this works</p>     

 <button>The Button</button>

 <form>
 First name: <input type="text" name="firstname"><br>
 Last name: <input type="text" name="lastname"><br>
 <input type="checkbox" name="yes" value="yes">A checkbox<br> 
 <input type="submit" value="Login">
 </form> 

in the above HTML snippet, If I use the below function, getting the button works yet getting the submit button does not.

 window.onload = theFunction;

 function theFunction(){

 document.getElementsByTagName("BUTTON")[0].setAttribute("onclick", "theOtherFunction()");

 document.getElementsByTagName("INPUT")[3];.setAttribute("onclick", "theOtherFunction()");

 }

What am I doing wrong?

 function theOtherFunction(){

   document.getElementById("ptag").style.color = "blue";

 }

I added theOtherFunction() to my question because all my little experiment is doing is changing that <p> color to blue. With the button, it stays blue. With the submit button, it quickly turns blue and then goes back to black. What is the difference and how can I use the submit button to retain changes?

Upvotes: 6

Views: 24412

Answers (3)

user4723924
user4723924

Reputation: 41

It's not practical to target/retrieve specific input elements with getElementsByTagName.

We gotta use the right tool for the right job and in this case it's the query selector like this...

var S=document.querySelectorAll('input[type=submit]');

S[0].style.background='red'; // do something to the first button

NB: Code above assumes you only have one submit button or you'll have to loop through the array "S" to target all submit buttons.

Upvotes: 4

Wayne Smith
Wayne Smith

Reputation: 4868

jQuery becomes very useful here

$('input[type="submit"]')

This will allow you to make html changes with immunity and support older browsers that still have 1% usage.

Your 2nd example should work without the ; in the middle of the line. However not all browsers support getElementsByTagName.

Update using no ready made libs.

If you are a build it yourself person, who wants to make his own lib.

function getElementsByAttrib(attrib) {
    return document.querySelectorAll('[' + attrib + ']');
}
var elements = getElementsByAttrib('type="submit"');
MySubmit = elements[0]';

Upvotes: 4

Luanf
Luanf

Reputation: 172

Take a look at your last line of code document.getElementsByTagName("INPUT")[3];.setAttribute("onclick", "theOtherFunction()");

There is a ; you don't want there right after the [3]. Hope this helps.

Upvotes: 4

Related Questions