Reputation: 16080
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
Reputation: 51
Check out the jQuery .one() event handler.
$("#my-button").one('click', function() {
/* Do something at most once */
});
Upvotes: 1
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);
});
Upvotes: 0
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
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)
Upvotes: 3
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