2

This is a simple example to call a JS function when a button is clicked. In this code I used the onclick method, but I want to learn how to call the same method using jQuery instead.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script> 
$(document).ready(function(){
    $("#but").click(
        doubleSize($("#inpt").val()); // **maybe not correct here**
    );
});
function doubleSize(x)
{
    //some code make a number double size
}
</script>
</head>

<body>

<input id="inpt" type="text">
<button id="but" type="button" onclick="doubleSize(document.getElementById('inpt').value)" >click me !!</button>
<div><span id="result"></span>
</div>
</body>
</html>
1
  • 1
    If you are going to do a jQuery event handler there is no need to use the onClick attribute for the element. You are already listening for that event. Commented Dec 5, 2013 at 15:15

1 Answer 1

7

Replace

    $("#but").click(
      doubleSize($("#inpt").val()); // **maybe not correct here**
    );

with

    $("#but").click(function() {
      doubleSize($("#inpt").val());
    });

Now it should work. The trick is that .click function has callback function which controlls doings after click, and you now learned to use it.

Check my fiddle.
Find more on api.jquery.com/click.

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

3 Comments

They'll also need to remove the inline js.
You mean onclick method? Yes I did just to show how I did to work.
No, jQuery's alternative for onclick is .click. See my demonstrative JSFiddle: jsfiddle.net/Mwx3w

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.