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.
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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With