0

I am facing a problem calling a function on click. The following is my code:

JavaScript:

$(document).ready(function(){       
    function showMessage(msg) {
        alert(msg);
    };      
})

HTML:

<input type="button" value="ahaha"  onclick="$(this).showMessage('msg');" />

for some reasons I cant use click() function. Please help me.

4 Answers 4

4

A few things:

  • showMessage() isn't a property of the jQuery object. It's just a regular function.
  • If you're using jQuery, don't use onclick. Bind all events with JavaScript.

There are a few ways of fixing this code. Here's one:

JavaScript:

$.fn.showMessage = function(message) {
  alert(message);
};

$(document).ready(function() {  
  $('#button').on('click', function() {
    $(this).showMessage('I am a message');
  });
});

HTML:

<input type="button" value="ahaha" id="button" />
Sign up to request clarification or add additional context in comments.

4 Comments

From all possible solutions, extending the jQuery object just makes the function more complex to call and adds the overhead of creating an unnecessary jQuery object..
What if showMessage() modifies the current object (hence the $(this)) to show the message?
I'll +1 as you're binding the listener, OP may decide what's important to keep or not besides that.
I liked the first point. To the point. Also the solution is quite cleaner and oo way :) +1
1
$(document).ready(function(){      
        function showMessage(msg) {
       alert(msg);
    };      <-----  i think this semicolon is not needed
        })  <-----  Should provide semicolon here as its the main function ending

1 Comment

That extra semi-colon doesn't make difference. ASI takes care of the lacking semi-colon.
1

without $(this) please.. Just call like this: onclick="showmessage('msg')"

2 Comments

I am on the phone man, i canot find the symbol for emphasizing the code :D
There, fixed the code. But I think there's still a closure problem with the function definition..
0

there are a few ways of doing this.

Let me make a few changes to your html,

<input id="myTest" value="CLICK ME!!!" title="HELLO WORLD!!!" type="button" />

next lets look at how to do this with jQuery

$(document).ready(function() {
  $('input#myTest').click(function() {
    var el = $(this),
        msg = el.attr('title');
    alert(msg);
  });
});

Hope this helps, Cheers

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.