Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  69] [ 1]  / answers: 1 / hits: 55913  / 11 Years ago, mon, december 30, 2013, 12:00:00

I have two buttons like this:



<button class=medium id=register type=button
onclick=location.href='/Account/Register'>Register</button>
<button class=medium default id=login type=submit>Login</button>


My Javascript selects the button by id:



<script type=text/javascript>
(function () {
document.getElementsByClassName('form')[0]
.addEventListener(submit, function (ev) {
document.getElementById('login').innerHTML += '&nbsp;<i class=fa fa-spin fa-spinner data-ng-show=fetching.length > 0></i>';
}, false);
})();
</script>


How can I change this so the javascripts selects the button with a type of submit or a
button with a class of submit if that's not possible?



Note that I would like to do this because the javascript is used by many forms. I need a common way to find the submit button.


More From » javascript

 Answers
15

You can use .querySelector() to find the first element matching a CSS style format selector - it works as a method of document to search (obviously) the whole document, or as a method of an element to search within only that element:



document.querySelector('button[type=submit]').innerHTML += '&nbsp;...';
// OR
someElement.querySelector('button[type=submit]').innerHTML += '&nbsp;...';


The latter is probably most useful to you since you want to find a submit button that presumably is in a form, and you already have a reference to the form: within a submit handler attached to the form with addEventListener() you can use this.querySelector(...).



Demo: http://jsfiddle.net/h6uuN/



The .querySelector() method is supported by pretty much all modern browsers, but (as always) a note about IE: supported from IE8 onwards. But since you're using addEventListener() presumably you don't care about old IE anyway.



If you did need to support old versions of IE you can use .getElementsByTagName() to find all button elements and then loop through them looking for the one that has type=submit.


[#73486] Saturday, December 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
earllutherf

Total Points: 412
Total Questions: 108
Total Answers: 102

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;