How can I unobtrusively disable submit buttons with Javascript and Prototype?

后端 未结 4 1646
失恋的感觉
失恋的感觉 2021-01-25 03:19

So I found this recommendation, but I can\'t quite seem to figure out how.

This is the code I originally started with:

   function greySubmits(e) {
              


        
4条回答
  •  悲哀的现实
    2021-01-25 04:08

    Here's what I came up with, which is adapted from above. Fixed so that it detects a cancelled event propagation using Prototype's stopped attribute.

    Other changes include using longer variable names (I always get confused about whether e is event or element), and a function that removed the replacement inputs if the form submission is cancelled. In my implementation pressing back on the browser doesn't show the page as it was when the user left it, instead it seems to be refetched (I'm using Rails), so I've removed that part too.

    I'm using buttons rather than inputs in my application so that part has changed also.

    function replaceSubmit(event) {
        var element = event.element();
        Element.insert(element, { 'before': ''});
    }
    
    function removeReplacementSubmits() {
        $$('input.button_replacement').each(function(button) {
            button.remove();
        });
    }
    
    function greySubmits(event) {
        // Don't disable the submit if the submit was stopped with a return(false)
        if (event.stopped === true) {
            removeReplacementSubmits();
        } else {
            $$('button[type="submit"]').each(function(button) {
                button.disabled = true;
                button.innerHTML += '…';
            });
        }
    }
    
    Event.observe(window, 'load', function() {
        $$("button[type='submit']").each(function(element) {
            Event.observe(element, 'click', replaceSubmit);
        });
        $$("form").each(function(element) {
            Event.observe(element, 'submit', greySubmits);
        });
    });
    

提交回复
热议问题