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

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

Related

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 simulate a dataTransfer object? [duplicate]

I'm currently attempting to test some code that uses drag-and-drop. I found some other questions that were kinda related to this, but they were way too specific to help me, or not related enough.
This being a test, I'm struggling on trying to automatically execute code inside a .on('drop',function(e){....} event. The main issue is not that I can't run the code inside, but it's that I can't transfer the dataTransfer property, and I can't seem to fake it because it's read-only. Is there anyway to fake the dataTransfer property or otherwise get around it?
I came up with this JSFiddle that serves as a template of what I'm trying to do: https://jsfiddle.net/gnq50hsp/53/
Essentially if you are able to explain to me (if this is at all possible) how I can possibly fake the dataTransfer property, I should be all set.
Side notes:
I'm totally open to other ways of somehow getting inside that code, like for example, maybe its possible to trigger the event and pass in a fake event object with a fake dataTransfer object.
To see the drag-drop behavior, change the JavaScript load type from no-wrap head to on-Load, then you should see what I'm trying to simulate.
Important to note that I cannot modify any of the code inside the event handlers, only inside the outside function
Using Karma/Jasmine so use of those tools are also possible like spies
Also, I'm using Chrome.
Thanks in advance, and let me know for any questions/clarifications!
You should be able to override pretty much everything you want using Object.defineProperty. Depending on what you want to test it can be very simple or very complex. Faking the dataTransfer can be a bit tricky, since there's a lot of restrictions and behaviors linked to it, but if you simply want to test the drop function, it's fairly easy.
Here's a way, this should give you some ideas as to how to fake some events and data:
//Event stuff
var target = $('#target');
var test = $('#test');
test.on('dragstart', function(e) {
e.originalEvent.dataTransfer.setData("text/plain", "test");
});
target.on('dragover', function(e) {
//e.dataTransfer.setData('test');
e.preventDefault();
e.stopPropagation();
});
target.on('dragenter', function(e) {
e.preventDefault();
e.stopPropagation();
});
//What I want to simulate:
target.on('drop', function(e) {
console.log(e)
//Issue is that I can't properly override the dataTransfer property, since its read-only
document.getElementById('dataTransferDisplay').innerHTML = e.originalEvent.dataTransfer.getData("text");
});
function simulateDrop() {
// You'll need the original event
var fakeOriginalEvent = new DragEvent('drop');
// Using defineProperty you can override dataTransfer property.
// The original property works with a getter and a setter,
// so assigning it won't work. You need Object.defineProperty.
Object.defineProperty(fakeOriginalEvent.constructor.prototype, 'dataTransfer', {
value: {}
});
// Once dataTransfer is overridden, you can define getData.
fakeOriginalEvent.dataTransfer.getData = function() {
return 'test'
};
// TO have the same behavior, you need a jquery Event with an original event
var fakeJqueryEvent = $.Event('drop', {
originalEvent: fakeOriginalEvent
});
target.trigger(fakeJqueryEvent)
}
https://jsfiddle.net/0tbp4wmk/1/
As per jsfiddel link you want to achieve drag and drop feature. jQuery Draggable UI already provides this feature why you can not use that?
For create custom event on your way you have to follow two alternative ways
$('your selector').on( "myCustomEvent", {
foo: "bar"
}, function( event, arg1, arg2 ) {
console.log( event.data.foo ); // "bar"
console.log( arg1 ); // "bim"
console.log( arg2 ); // "baz"
});
$( document ).trigger( "myCustomEvent", [ "bim", "baz" ] );
On above example
In the world of custom events, there are two important jQuery methods: .on() and .trigger(). In the Events chapter, we saw how to use these methods for working with user events; for this chapter, it's important to remember two things:
.on() method takes an event type and an event handling function as arguments. Optionally, it can also receive event-related data as its second argument, pushing the event handling function to the third argument. Any data that is passed will be available to the event handling function in the data property of the event object. The event handling function always receives the event object as its first argument.
.trigger() method takes an event type as its argument. Optionally, it can also take an array of values. These values will be passed to the event handling function as arguments after the event object.
Here is an example of the usage of .on() and .trigger() that uses custom data in both cases:
OR
jQuery.event.special.multiclick = {
delegateType: "click",
bindType: "click",
handle: function( event ) {
var handleObj = event.handleObj;
var targetData = jQuery.data( event.target );
var ret = null;
// If a multiple of the click count, run the handler
targetData.clicks = ( targetData.clicks || 0 ) + 1;
if ( targetData.clicks % event.data.clicks === 0 ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = handleObj.type;
return ret;
}
}
};
// Sample usage
$( "p" ).on( "multiclick", {
clicks: 3
}, function( event ) {
alert( "clicked 3 times" );
});
On above example
This multiclick special event maps itself into a standard click event, but uses a handle hook so that it can monitor the event and only deliver it when the user clicks on the element a multiple of the number of times specified during event binding.
The hook stores the current click count in the data object, so multiclick handlers on different elements don't interfere with each other. It changes the event type to the original multiclick type before calling the handler and restores it to the mapped "click" type before returning:

jQuery focus blur pass parameter

I can't seem to access the variable defaultValue down in my .blur() function. I've tried various stuff but with no luck. So far I only get an empty object. What's wrong?
jQuery(document).ready(function(){
jQuery('#nameInput, #emailInput, #webInput').focus(function(){
var defaultValue = jQuery(this).val();
jQuery(this).val("");
})
.blur(function(defaultValue){
if(jQuery(this).val() == ""){
jQuery(this).val(defaultValue);
}
});
});
Looks like the question is about the passing data into the .blur or .focus event.
per jQuery API - http://api.jquery.com/blur/
blur( [eventData ], handler(eventObject) )
So if you want to pass data - you can send a parameter to event - which will appear as data in event object.
see this fiddle for more info
http://jsfiddle.net/dekajp/CgP2X/1/
var p = {
mydata:'my data'
};
/* p could be element or whatever */
$("#tb2").blur(p,function (e){
alert('data :'+e.data.mydata);
});
Because your code is wrong :-) you define var inside function (var defaultValue) which is then immediately wiped out.
There are two solutions: define your var as a global var before you bind blur event, or store it in the data of object liket his (which I recommend):
$(document).ready(function(){
$('#nameInput, #emailInput, #webInput').focus(function(){
$(this).val("").data('defaultValue',jQuery(this).val());
}).blur(function(defaultValue){
if($(this).val() == ""){
$(this).val($(this).data('defaultValue'));
}
});
});
It seems to me that you don't understand the basics of JavaScript.
First of all variables in JS are localized to function's scope, so you can't declare variable with var in one function and access it in other function
Second, you can't pass anything to DOM-event handler, except event-object, this is defined by the DOM specification, sometimes you can use event data parameter to the blur jQuery method.
Try this:
jQuery(document).ready(function(){
var defaultValue;
jQuery("#nameInput, #emailInput, #webInput").focus(function(){
defaultValue = jQuery(this).val();
jQuery(this).val("");
})
.blur(function(){
if(jQuery(this).val() == ""){
jQuery(this).val(defaultValue);
}
});
});
First of all, you need to distinguish blur method (function) and handler (function) which is the argument to the blur. You was trying to pass the defaultValue exactly to handler, but that can't be done. Inside handler the defaultValue would be equal eventObject, so you can do smth like console.log(defaultValue.timeStamp) and you'll see smth like 123482359734536
In your approach you can't even use event.data argument to the blur cause it will be set at the time of blur's call (attaching handler). You need to declare a var outside of the both handlers, so it will be visible to both of them
You may consider to read some comprehensive book on JS.
I read "Professional JaveScript For Webdevelopers" by Nicolas Zakas. There is a new edition

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

How do I redefine `this` in Javascript?

I have a function which is a JQuery event handler. Because it is a JQuery event handler, it uses the this variable to refer to the object on which it is invoked (as is normal for that library).
Unfortunately, I need to manually call that method at this point. How do I make this inside the called function behave as if it were called from JQuery?
Example code:
function performAjaxRequest() {
//Function which builds AJAX request in terms of "this"
}
function buildForm(dialogOfForm) {
var inputItem;
dialogOfForm.html('...');
dialogOfForm.dialog('option', 'buttons', {
"Ok" : performAjaxRequest
});
inputItem = dialogOfForm.children(':not(label)');
//Redirect enter to submit the form
inputItem.keypress(function (e) {
if (e.which === 13) {
performAjaxRequest(); //Note that 'this' isn't the dialog box
//as performAjaxRequest expects here, it's
//the input element where the user pressed
//enter!
}
}
}
You can use the function's call method.
someFunction.call(objectToBeThis, argument1, argument2, andSoOnAndSoOn);
If dialog is the object that you need to be set to this then:
performAjaxRequest.apply(dialog, []);
// arguments (instead of []) might be even better
should do the trick.
Otherwise, in jQuery you can simply call the trigger method on the element that you want to have set to this
Say, for example, that you wanted to have a click event happen on a button and you need it to happen now. Simply call:
$("#my_button").trigger("click");
Your #my_button's click handler will be invoked, and this will be set to the #my_button element.
If you need to call a method with a different this ... say for example, with this referring to the jQuery object itself, then you will want to use call or apply on your function.
Chuck and meder have already given you examples of each ... but to have everything all in one place:
// Call
my_function.call(object_to_use_for_this, argument1, argument2, ... argumentN);
// Apply
my_function.apply(object_to_use_for_this, arguments_array);
SEE: A List Apart's Get Out of Binding Situations
Are you looking for..
functionRef.apply( objectContext, arguments);
You should of course learn to master call() and apply() as people have stated but a little helper never hurts...
In jQuery, there is $.proxy. In pure js, you can re-create that niftyness ;) with something like:
function proxyFn( fn , scope ){
return function(){
return fn.apply(scope,arguments);
}
}
Usage Examples:
var myFunctionThatUsesThis = function(A,B){
console.log(this,arguments); // {foo:'bar'},'a','b'
};
// setTimeout or do Ajax call or whatever you suppose loses "this"
var thisTarget = {foo: 'bar'};
setTimeout( proxyFn( myFunctionThatUsesThis, thisTarget) , 1000 , 'a', 'b' );
// or...
var contextForcedCallback = proxyFn( myAjaxCallback , someObjectToBeThis );
performAjaxRequest(myURL, someArgs, contextForcedCallback );
If you dont abuse it, it's a sure-fire tool to never loose the scope of "this".
use a closure
i.e assign this to that early on; then you can do what you like with it.
var that = this;

Categories