Tuesday, March 1, 2011

how to disable a image button that acts as submit button

I have a image button thats acts as a form submit button:

<a href="#" onClick="submitComment('+[id]+'); return false;"><img class="submitcommentimg" id="submitcommentimg<?php echo $id; ?>" src="/images/check.png" alt="Comment!" border="0"></a>

What is the best way to 'disable' it to prevent accidental double clicking.

From stackoverflow
  • Remove the onclick handler on the anchor upon clicking on it.

    Example:

    <a href="#" onclick="/* .. do all your things ... */ this.onclick = function(){}; return false;">
    
    ian : example please?
    thephpdeveloper : example written. notice the `this.onclick = function(){};` it removes the current onclick function that is binded.
    Neil Sarkar : this.onclick = null works too
    thephpdeveloper : @Neil - yep that's correct! Pardon me, because I work with jQuery frequently, typing `function(){}` is rather common for me.
    ian : Both those work.. But... Jump the page to the top... How can I prevent that.
    thephpdeveloper : jumping the page to the top is disabled by returning false.
  • Change your onclick attribute to something like this:

    onclick="submitComment('+[id]+'); this.onclick='return false;'; return false;"
    
    ian : How do I add that in with JavaScript
    ian : Oh I get it... You do down command in the onClick...
  • removing the onclick handler sounds like the right answer, if you need more information on what and how please go to http://www.quirksmode.org/js/events%5Ftradmod.html

  • Use <input type="image" src="/images/check.png" alt="Comment!"> instead. This will act as a submit button, with the added advantage of not requiring JavaScript. There's no good reason to use JavaScript to replicate things that HTML can already do perfectly well.

    ian : But I am calling a function not just submitting a form.
  • The best way is to make a "Submitting..." image and change the code like this:

    <a href="#" onclick="this.onclick = "return false;"; this.getElementsByTagName('img')[0].src="/images/submitting.png"; submitComment('+[id]+'); return false;">
        <img class="submitcommentimg" id="submitcommentimg<?php echo $id; ?>" src="/images/check.png" alt="Comment!" border="0">
    </a>
    

    ...or something like that.

    In this example the image is called "submitting.png".

    ian : So it changes its own code? Wouldn't I want to call my function first then change it?
    Kaze no Koe : It clears it's own onclick attribute so that nothing happens the second time the visitor clicks on it. Switching to a different image that says something like "Submitting..." lets the user know that his input has been accepted and is being processed.

0 comments:

Post a Comment