0

I have this simple jQuery script that asks to confirm action when you click on a link. And it works great when it's a normal a href link, but I have onclick script assigned to the button and it does not prevent it from firing. I need it to prevent it only once. How can I achieve that?

$(".mybutton").one('click', function() {
    event.preventDefault();
    $(this).html("Are you sure?");   
});

function test() {
  $(".forthebutton").html("button click function worked");  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="mybutton" onclick="test();">Button</button>

<br /><br /><br />

<span class="forthebutton">button click should change this text</span>

1
  • On clicking the button, you are intending to change both the text in the span with class "forthebutton" and also ask confirmation? Is this understanding correct? Commented May 30, 2020 at 17:01

1 Answer 1

1

You need to remove original onclick and give it back in this case because you can't influent on onclick handler.

const btn = $(".mybutton");
const onclick = btn.prop('onclick'); // save onclick fn

btn.prop('onclick', null); // remove onclick from button
btn.one('click', function() {
    $(this).html("Are you sure?");
    btn.on('click', onclick); // add onclick back to button
});

function test() {
  $(".forthebutton").html("button click function worked");  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="mybutton" onclick="test();">Button</button>

<br /><br /><br />

<span class="forthebutton">button click should change this text</span>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.