Pass arguments from a button click to Jquery event handler - javascript

I am trying to pass the argument to the JQuery event handler when a button is being clicked. In plain JavaScript i was using onclick="function(argument)"
Now i am transferring all of my inline click events to external call like one with Jquery i.e
$(".selector").click(function(){
//some code
});
However, in this case i am confused how i can pass the arguments from the HTML tag and how should i receive the arguments in the Jquery event handler.
Please help.

An optional object of data passed to an event method when the current executing handler is bound.
In your case it will be something like this -
$(".selector").on("click", function(event){
//you can access the parameter value as follows
console.log(event.target.value);
});
Refer the official documentation here Pass arguments from a button click to Jquery event handler

The .click() function receives an EventData object that gets passed as the first argument to the handler, you can use that object inside the handler.
For example:
$('.selector').click(function(data) {
$(data).addClass('newClass');
});
If you are trying to pass data from the HTML the cleanest way might be to store that data into the data attribute of your tag.
The HTML
<div id="mydiv" data-arg="Hello world!">Click me</div>
The JS
$('#mydiv').click(function(data) {
var arg = $(data).attr('data-arg');
console.log(arg);
});
For what you are trying to achieve
The HTML
<button id="dark" data-stroke-width="0.5"
class="txtcolor uk-button" type="button">1px</button>
The JS
$('button#dark').click(function(data) {
selectStroke($(data).attr('data-stroke-width'));
});
Check the documentation for click

A sample:
// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
var param_obj = {data : {param1: "Hello", param2: "World"}};
cool_function(param_obj);
$("dark").click({param1: 0.5}, selectStroke);
or
var i = 0.5;
$("dark").click({param1: i}, selectStroke);
or if you do not want change functionality of the handler
var i = 0.5;
$("dark").click({param1: i}, function() {
selectStroke(event.data.param1);
);

Related

Converting jQuery .change() to plain JavaScript/DOM

I'm developing an autofill extension. I want to fill an input field with a value, example value = "12345", and then trigger the equivalent of a jQuery $(element).change(), but in pure JavaScript/DOM.
I've tried dispatching the change method,
document.querySelector("input[name=inputIWantToChange]").dispatchEvent(new Event("change"));
but the behavior is different than that of
$("[name=inputIWantToChange]").change()
Looking at jQuery's source code, it would appear that jQuery works by invoking the handler that you have bound to the event (with a fake event that it creates) when you call change() - which means that you're going to have to find a way to be able to invoke a function, and also have the event invoke the same function. Consider the following:
var elem = document.querySelector("input[name=inputIWantToChange]");
elem.addEventListener("change", function (evt) {
onElemChange() // Pass data from the event `evt` here, as needed
});
function onElemChange() {
// Your handler method here
}
When you'd want to invoke a "change event" as you do with jQuery, you can then just call onElemChange with the information you'd have gotten from the event, assuming you'd want to use any of the information from the event.

Pass input parameter to .click event

I have a function as follows:
$("#submitBtn").on('click', function () {
....
});
I am using the following in invoke the click it in a portion of code by doing:
$('#submitBtn').click();
Is there a way to set a input parameter to the click.
For example, I need to pass a string value to the click so that the function can take appropriate steps. Note that the value of p is not from any element from the page. It is something I will be pro-grammatically setting based on some conditions.
var p = 'sourceinfo';
$('#submitBtn').click(p);
Alright, the best way to do this is by adding custom data-attribute params to the element before chaining it with the click event:
$("#submitBtn").data("params", {
one: "Parameter 1",
two: "Parameter 2"
}).click();
And you can use params like this:
$("#submitBtn").on('click', function () {
// Parameter 1
alert( $(this).data("params").one );
// Parameter 2
alert( $(this).data("params").two );
// Do other stuff
});
Check working demo
You can use the event handler .trigger() instead of .click()
Syntax :
.trigger( eventType [, extraParameters ] )
Example:
.trigger('click',[param1,param2])
After that you can get those params from your call back function after event param
Click is a event generated and cannot pass the message/data. Instead you can pass the args to the listener(calling method).so that it can be captured to that method.
for e.g
<button onclick="handleClick('msg',event)"></button>
You can use .trigger() instead.
$('#submitBtn').trigger('click', [arg1, ...]);
You can retrieve the parameters passed when attaching the click handler
$('#submitBtn').on('click', function(e, arg1, ...) {
});
You can you jQuery(this).attr('action') ... Inside the function
And on the element add attribute as follow data-action('myaction')

How to pass parameter on change function JQuery [duplicate]

I'm using jQuery version 1.5.
I am looking at jQuery's change() function
and specifically at this bit:
.change( [ eventData ], handler(eventObject) )
eventData: A map of data that will be passed to the event handler.
handler(eventObject): A function to execute each time the event is triggered.
What exactly is a "map of data" in JavaScript? How can I use the following test function as an event handler?
var myHandler = function(msg){alert(msg);};
I've tried this:
$("select#test").change(["ok"], myHandler);
and the alert reports [object Object]
See event.data. The data is not passed as argument to handler, but as property of the event object:
$("select#test").change({msg: "ok"}, function(event) {
alert(event.data.msg);
});
The handler always only accepts one argument, which is the event object. This is the reason why your alert shows "[object Object]", your function is printing the event object.
If you want to use functions with custom arguments, you have to wrap them into another function:
$("select#test").change({msg: "ok"}, function(event) {
myHandler(event.data.msg);
});
or just
$("select#test").change(function(event) {
myHandler("ok");
});
Btw. the selector is better written as $('#test'). IDs are (should be) unique. There is no need to prepend the tag name.
What exactly is a "map of data" in Javascript?
Basically just an object, e.g.:
var data = {
foo: "I'm foo",
bar: "I'm bar"
};
All JavaScript objects are essentially maps (aka "dictionaries" aka "associative arrays").
How can I use the following test function as an event handler?
By wrapping it in another function:
$("select#test").change(function() {
myHandler($(this).val());
});
That calls myHandler with the value of the select box whenever it changes.
If you want to use the eventData part, add an object prior to the handler:
$("select#test").change({
foo: "I'm foo"
}, function(event) {
myHandler(event.data.foo, $(this).val());
});
That calls myHandler with the "I'm foo" as the first argument, then the value of the select box, whenever it changes.

jQuery event.PreventDefault not working in User Defined Function

I am creating a function which will take in a URL and then display that URL in a light box. I am having trouble with event.preventDefault() in my function though, it says it is not a function in the error console.
I have tried explicitly passing event to the function but that simply runs the function on page load rather than when clicking
Here is my code:
// Function to display widget
function displaySportsWidget(event, iframeURL) {
// Prevent Default Event Handler
event.preventDefault();
// Build iFrame HTML
var iframe = '<iframe src="' + iframeURL + '" ></iframe>';
var html = iframe;
// Inject HTML to Generate Widget
$('.leagues-wrapper').html(html);
// Display Overlay
$('.leagues-overlay').css('display', 'block');
};
// Event handlers. Pass iFrame URL into function depending on link clicked
$('.leagues-link.league-table').on('click', displaySportsWidget('http://www.example01.com'));
$('.leagues-link.league-form').on('click', displaySportsWidget( 'http://www.example02.com'));
The code
$('.leagues-link.league-table').on('click', displaySportsWidget('http://www.example01.com'));
calls displaySportsWidget and passes its return value into on, exactly the way foo(bar()) calls bar and passes its return value into foo.
If you want to hook up an event handler, you don't call it, you just refer to it. In your case, you can do that like this:
$('.leagues-link.league-table').on('click', function(e) {
displaySportsWidget(e, 'http://www.example01.com');
});
Or if you're open to changing the order of arguments in displaySportsWidget:
function displaySportsWidget(iFrameURL, event) {
// ...
}
...then you can use Function#bind:
$('.leagues-link.league-table').on('click', displaySportsWidget.bind(null, 'http://www.example01.com'));
Function#bind creates a new function that, when called, calls the original function with a given this value (in our case, we don't need any specific one, so I'm passing null) and any arguments you gave bind, followed by any arguments that were given to the bound function. So we'll get the URL (from the bind call) followed by the event object (from when the handler is called).
Function#bind isn't on really old browsers like IE8. If you need to support them, jQuery's $.proxy does something similar:
$('.leagues-link.league-table').on('click', $.proxy(displaySportsWidget, null, 'http://www.example01.com'));
While calling your method you are not passing event as parameter along with image url .so if u pass event as parameter while calling.then your code is going to work.
Thank you

Access custom attributes via jquery

I need to access to the custom attribute or data of my link but I can't. My code is simple yet in repeater. I don't know if this is causing a problem. Here is the code:
<a class="showAllComm" data-userid='<%# DataBinder.Eval(Container.DataItem, "USER_ID")%>' href="#sa">Show all comments</a>
Here is my click event:
$('.showAllComm').click(function(index, element) {
var commId = $(element).data("userid");
})
commId is undefined but I can see it in the source code that it has value of 1.
how can I access to the userId?
Thank you
Reference the element with this instead of the second parameter:
var commId = $(this).data("userid");
The arguments passed to an event handler are not the index and element as you'd have in .each().
By default, you just get a single event argument passed.
DEMO: http://jsfiddle.net/Jjbwd/
$('.showAllComm').click(function( event ) {
alert( event.type ) // click
var commId = $(this).data("userid");
});
The data method is not a shortcut for the attr method. It takes an element and an attribute, per the docs
Just use attr("data-userid")

Categories