Pass input parameter to .click event - javascript

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')

Related

Pass arguments from a button click to Jquery event handler

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);
);

pass a parameter in setAttribute "onclick" function argument in javascript

Here in line no 163 I want to set a function to the close item . close is a button here . And I want to pass a parameter through it's "onclick" event. that is it's id. How do I do it?
You better use an event listener in this case instead of try to manipulate the onclick with setAttribute:
close.addEventListener("click", function(){
//do what you need here: call another function, do some math, etc...
checker('id'); //???
});
You can use:
close.onclick = function(){
checker('id'); // <-- are you sure you want to pass static string here?
};

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.

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")

Sending $(this) on an onchange on the current element

I have this html
<select class="category" style="margin-bottom: 5px;" onchange="getProducts('standard_product');">
and as you can see the onchange calls the getProducts function. I want to know if there is a way to sent in this like
<select class="category" style="margin-bottom: 5px;" onchange="getProducts('standard_product', $(this));">
which i would hope would be associated to the current select
If you're trying to set the value of this in your function, you can use .call:
onchange="getProducts.call(this, 'standard_product');"
Now in your getProducts function, this will be the element that received the event.
function getProducts( prod ) {
alert( this ); // the <select> element
}
You can also pass along the event object:
onchange="getProducts.call(this, 'standard_product', event);"
...and reference it in your function:
function getProducts( prod, e ) {
alert( this ); // the <select> element
alert( e.type ); // the event type
}
EDIT: As noted by #Cybernate, this is setting the DOM element to this. You'll need to wrap it in your getProducts function $(this), or set it as such in your inline handler.
Though setting this to the element itself is more in line with typical event handler behavior.
EDIT: To further explain what .call does, it allows you to manually set the value of this in the function you're calling.
Take this function, which simply alerts this:
function some_func() {
alert( this );
}
Calling it in a basic manner (in a browser) makes this reference the DOM Window.
some_func(); // the alert will be DOM Window
But now lets invoke using .call, and setting the first argument to 123.
some_func.call( 123 ); // the alert will be 123
You can see that now the alert shows 123. The function hasn't changed, but the value of this has because we've manually set it using .call.
If you have additional arguments to send, you just place them after the thisArg.
function some_func( arg1 ) {
alert( this );
alert( arg1 );
}
some_func.call( 123, 456 );
The this alert will be 123, and the next argument you send will be set to the arg1 parameter, so arg1 will be 456.
So you can see that call basically slices off your first argument you send, sets it as the value of this, and sets the remaining arguments as your normal arguments associated with your function parameters.
You can try:
onchange="function(){var $this = $(this); getProducts('standard_product', $this)}"
To make it much better get rid of the inline event handler assignment as below:
$(function(){
$(".category").click(function(){
var $this = $(this);
getProducts('standard_product', $this);
});
})

Categories