Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments into JQuery function?

Tags:

html

jquery

I want to pass a value to a Jquery function. Below is the Javascript sample code. I want to convert this javascript function to a jquery function. How can I pass the state name into a jquery onclick function?

<a onclick="showState('state_name')">ADD STATE </a>

 function showState(state_name){
 openbox_state(state_name);
 }

please help me.

like image 323
sjkon Avatar asked Nov 15 '12 06:11

sjkon


People also ask

What is $() in jQuery?

In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: 1. $( "div.

How can you get the type of arguments passed to a function?

Passing Arguments There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.

How parameters are passed to functions in JavaScript?

Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.

How do you pass an Array as an argument to a function in JavaScript?

Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.


1 Answers

You don't really make it clear whether you have a series of anchors to add different states, or...?

If you do, you can do something like this to record the appropriate state name for each link:

<a data-stateName="state_name">ADD STATE </a>

And then in JS, with jQuery:

$(document).ready(function() {
    $("a[data-stateName]").click(function() {
        openbox_state( $(this).attr("data-stateName") );
    });
});

This removes the inline JavaScript from your html, and then uses jQuery to bind a click handler only to those <a> elements that have a data-stateName attribute. The handler then gets the value of that attribute to pass to the openbox_state() function.

The document ready handler ensures that the anchor click binding doesn't happen until the document actually is ready, i.e., after the elements have been parsed and can be accessed from JS. (You don't need a ready handler if you put your JS in a script block at the end of the body element.)

like image 115
nnnnnn Avatar answered Oct 22 '22 10:10

nnnnnn