bartektartanus
bartektartanus

Reputation: 16080

Html button action only on first click

I can set action on click for html button. But I need to set action only on FIRST click. Is there any way to do this? The button is radio in form. Some javascript maybe?

What's important - the radio button still might be changed. But action has to be done only once.

This doesn't work

function myfunction(i){
oForm = document.forms["myform"];
if(oForm.elements["field"+i].checked)
    alert("action done earlier");
else
    action
}

Upvotes: 0

Views: 5686

Answers (5)

Serf
Serf

Reputation: 51

Check out the jQuery .one() event handler.

$("#my-button").one('click', function() {
    /* Do something at most once */
});

Upvotes: 1

MrBoolean
MrBoolean

Reputation: 601

To resolve this problem I have used jQuery.on as well as jQuery.off - see my code on jsfiddle!

$(document).ready(function() {
    var button = $('#my-button');

    function onClick() {
        alert('clicked');
        button.off('click', onClick);
    };

    button.on('click', onClick);
});

http://jsfiddle.net/VxRyn/

Upvotes: 0

Marcandria
Marcandria

Reputation: 415

You could use a property to disable the button once it has been clicked, adding

disabled="disabled"

to the button once clicked ?

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382514

The cleanest solution is probably to use removeEventListener to... remove the event listener :

var myButton = document.getElementById('someId');
var handler = function(){
   // doSomething
   myButton.removeEventListener('click',handler);
}
myButton.addEventListener('click', handler);

(to make it cleaner, you could wrap this in an IIFE, as in the example below)

Demonstration

Upvotes: 3

m1k1o
m1k1o

Reputation: 2364

If you preffer jQuery, You can use jQuery unbind

$("button").click(function(){
  /* some content */
  $(this).unbind('click');
});

Html

<button> Some content </button>

Upvotes: 0

Related Questions