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.

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
Kamal
  • 2,140
  • 8
  • 33
  • 61

4 Answers4

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" />
Blender
  • 289,723
  • 53
  • 439
  • 496
1

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

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
doniyor
  • 36,596
  • 57
  • 175
  • 260
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
Dhanish
  • 11
  • 1
  • That extra semi-colon doesn't make difference. [ASI](http://stackoverflow.com/questions/7651231/what-does-asi-mean) takes care of the lacking semi-colon. – Fabrício Matté Jul 07 '12 at 05:16
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