Question

I cannot alter the following code, but instead must override the default functionality of the button so that when clicked, a custom javascript method is called instead of the form being submitted.

And to accomplish this I must use javascript via injection.(Its a AIR desktop app using the twitter api)

Can anyone help?

<body>
<form><fieldset class="buttons">
           <input class="submit button" id="cancel" name="cancel" type="submit" value="Cancel" />
</fieldset>
</form>
<body>
Was it helpful?

Solution

If you want to prevent form from submitting overiding click wont be enough. One can submit you form by Ctrl+Enter.

You can do the following http://jsfiddle.net/tarabyte/R5yQq/.

  1. Find the form assuming you know button id.

    function getForm(id) {
    
         var button = document.getElementById(id);
    
         while(button && 
              (button = button.parentNode) && 
              (button.nodeName !== 'FORM')){}
    
         return button;
    }
    
  2. Add 'submit' event listener.

    var form = getForm('cancel'),
        handler = function(ev){
        ev = ev || window.event;
        if(ev.preventDefault) { //w3c browsers
            ev.preventDefault();    
        }
        else { //IE old
            ev.returnValue = false;    
        }
        alert('Custom logic goes here!'); 
    };
    if(form) {
        if(form.addEventListener) {
           form.addEventListener('submit', handler, false)   
        }
        else if(form.attachEvent) {
           form.attachEvent('onsubmit', handler);   
        }    
    }
    

OTHER TIPS

Replace it via JS with a button that calls your function

document.getElementById('cancel').parentNode.innerHTML = '<input type="button" onClick="myFunc()" value="replaced">';
window.myFunc = function() { alert('clicked'); return false; }

http://jsfiddle.net/e37nd/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top