简体   繁体   中英

How can I select a button with a type of submit using Javascript?

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.

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" .

You can use querySelectorAll. It works back to IE8.

document.querySelectorAll('[type=submit]')

JS fiddle here http://jsfiddle.net/X2RLg/

You could get all buttons on the page by doing this:

var buttons = document.getElementsByTagName("button");

Then you can iterate through the array and find all buttons with 'submit' as the value of their type property.

var submits = [];
var i;
for(i = 0; i < buttons.length; i++) {
   if(buttons[i].type == "submit") { submits.push(buttons[i]); }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM