0

I have codes :

HTML :

<div class="modal-footer" >
     <button type="button" class="btn btn-sm btn-default" id="mybutton" style="background-color: #367E2D; color:white; opacity: 1" onclick="chooseme();">OK</button>
</div>

Javascript :

('#mybutton').click(chooseme('123'));

Purpose :

I want to change onClick event from chooseme() to chooseme('123') using Javascript

And the result of the code above is :

chooseme('123') executed immediately (not when the button clicked)

Question is : Anyone can explain what's wrong with my code? and what is the correct implementation to reach the purpose above?

1 Answer 1

6

I assume from the syntax that you're using jQuery. When binding events to named functions in JS, you need to pass the function itself to the callback. With your current syntax, you're passing the return value from chooseme() to the click handler. As a result, the function is called immediately on page load.

Wrap the hander inside an anonymous function, and you're good to go:

$('#mybutton').on('click', function() { chooseme('123') });
Sign up to request clarification or add additional context in comments.

1 Comment

sorry, i have found a problem, choseme executed twice. I don't have idea why. anyway thanks for your answer

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.