Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a simple function?

How do you create a function in jQuery, call it, and pass a variable to it? Here it is in Javascript style:

<script type="text/javascript">
function popup(msg) {
  alert(msg);
}
</script>

Then you would simply include the event in the HTML:

<html>
<input type="submit" onclick="popup('My Message')" />
</html>

What is the jQuery equivalent to doing this? From all the "newbie" tutorials, they are all static functions that do not accept variables. For example:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $('button').click(function() {
    alert('hello, world');
   });
});
</script>

I want to be able to dynamically include different messages. The code above affects all buttons and spits out the same message of 'hello, world'.

like image 300
user785179 Avatar asked Jun 14 '12 22:06

user785179


3 Answers

If you want the message to be dynamic, you're going to want to use data-attributes:

<input class='message-button-' type="submit" data-message="My Message" />

Then in a separate javascript file:

// equivalent of $(document).ready(function(){...
$(function(){

  // Functionality starts here
  $('.message-button').on('click', function(e){
    alert($(this).data('message'));
  })


});

Now the function will execute any time a button with class .message-button is clicked, and it will use the custom attribute data-message to display a message.

Hope this helps! :)

Update:

Note that it's considered best-practice to do javascript unobstrusively. Some people have mentioned still using the onclick attribute like you did in your example, don't do that. Bind the event like I've shown here using jquery's .on('click', function(){}) method.

If your click item is an anchor tag <a> then you can prevent the href from being followed if you want, by using e.preventDefault:

$('a').on('click', function(e){
  e.preventDefault()
})

Also in case you need to know, the $('.message-button') is using css selectors to grab dom elements. Any valid CSS selector will normally work in there.

Step-by-step

First, we need to wrap all of our code in a function provided by jQuery that waits until the document is ready to handle javascript actions and dom manipulation. The long-form version is $(document).ready(function(){ /* CODE GOES HERE */ }) but the version I've used is a shortcut $(function({ /* CODE GOES HERE */ }):

$(function(){
})

Next, we need to bind an event to our button. Since we've given it the class .message-button, we can use jQuery to grab that element and bind the 'click' event to it:

$(function(){
  // Functionality starts here
  $('.message-button').on('click', function(e){
    // Code here executes when the input button is clicked
  })


});

Inside of event handlers this is re-bound to point directly to the HTML element that triggered the event. Wrapping in $() gives us access to jquery methods. Thus: $(this) is used very frequently. jQuery gives us the .data() method to access any data-* methods on the element and give us the value, which is what the alert() is doing.

$(function(){
  // Functionality starts here
  $('.message-button').on('click', function(e){
    alert($(this).data('message'));
  })


});
like image 175
nzifnab Avatar answered Oct 08 '22 00:10

nzifnab


This is my best way to do this just like javascript:

---- Make function by using jQuery like this

<script>$(document).ready(function(){
    popup=function(msg){
      alert(msg);
    }});
</script>

And you don't need to change the code at the body

<html>
<input type="submit" onclick="popup('My Message')" />
</html>

Here is the sample http://jsfiddle.net/PLnF3/

---- But wait, If you just need to show an alert message maybe this sample is the best:

<html>
<input type="submit" onclick="alert('My Message')" />
</html>

You don't need any javascript or jQuery to do this, just use alert('My Message') on your button. Sample http://jsfiddle.net/PLnF3/1/

---- If you want a better appearance using jQuery, you can use jQuery Dialog().

Here the example http://howto.software-mirrors.com/2013/09/how-to-make-jquery-popup-window.html This is the code:

<script>
    $(document).ready(function() {
        popup = function(msg) {
            $("<div>" + msg + "</div>").dialog();
        }
    });
</script>

And you don't need to change the html code on your body.

<html>
<input type="submit" onclick="popup('My Message')" />
</html>

Here the example http://jsfiddle.net/PLnF3/2/

Remember, to be able to use jQuery dialog, you need jquery.js, jquery-ui.js and also jquery.css theme. read more at http://howto.software-mirrors.com/2013/09/how-to-make-jquery-popup-window.html

like image 31
Entaah Laah Avatar answered Oct 08 '22 00:10

Entaah Laah


You'd give each button a different ID, like so:

<input type="submit" id="submit-something" onclick="popup('My Message')" />

Then:

$(document).ready(function() {
    $('#submit-something').click(function() {
        alert('My message');
    });
});

Also, if the task is very repetitive, you can use another function to create the function:

function messageHandler(message) {
    return function() {
        alert(message);
    };
}

$(document).ready(function() {
    $('#submit-something').click(messageHandler('My message'));
});
like image 35
Ry- Avatar answered Oct 08 '22 00:10

Ry-