Trying to pass event data to function - javascript

I am trying to pass some data to a function but I'm facing an issue with the code below. I can't seem to make it work when i try to use $(this).data("id") if I just use ABC as a value it works.
$(".printLabel").click({
recordId: $(this).data("id")
}, printLabel);
function printLabel(event){
var data = event.data;
console.log(data.recordId);
}

Within the object you provide this is a reference to the window, not the clicked element, hence the data attribute you're looking for is undefined.
Assuming that the data attribute is on the .printLabel element itself, you can retrieve it within the event handler directly without sending any event arguments. Try this:
$(".printLabel").click(function() {
var recordId = $(this).data("id")
console.log(recordId);
});

Why is it a problem calling the function in a more understandable manner? Also if you insist on passing an object, you need to use the object passed - var data = event.data; would not work either. Here is my suggestion using an object too:
$(".printLabel").on("click",function() {
printLabel( {recordId: $(this).data("id")});
});
function printLabel(passedObject){
console.log(passedObject.recordId);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="printLabel" data-id="ID1">This is id1</div>

Related

Retrieve a value that i not bind

I have a form whre I add from controller the element:
oInput.setValue(oField.value);
oInput.attachValueHelpRequest(this.handleValueHelp).setShowValueHelp(true);
I have also oField.lookupOfSpecificInput, a string conains the function that I call on server; the lookup is different for each Input Field. The server answer with a list of suggestions.
In the handle help function I have:
handleValueHelp : function (oController) {
var lookupOfSpecificInput=???????????????????
if (! this._oDialog) {
this._oDialog = sap.ui.xmlfragment("sap.ui.demo.poa.view.fragment.FrgLookup", this);
}
this._oDialog.open();
}
How can I retrieve the value of lookup from the input for which I need a help?
You could try to proxy the handler trhough jQuery and pass "this" into it. Then you could fetch the value from "this" inside your handler.
oInput.attachValueHelpRequest($.proxy( this.handleValueHelp, this )).setShowValueHelp(true);
Dont know if that works in this context...

jQuery on click event function to be used as a normal function as well

I have a event handler method which executes on the click of a button. I also pass on some data as shown below
$( "button" ).on( "click", {name: "Hello"}, greet );
And the method is defined as:
function greet(event) {
// Use the data as event.data.name
// Access the DOM element on whose click this method was invoked as $(this)
}
But I also want to use this function as a normal js function.
How do I pass on the data ({name: "Namaskara"})?
How to set the context - For example say I have another button as <button id="kannada" /> and I want to use this button as the context and be sent to the greet() function so that the $(this) used in the function would actually be by button
1). To answer your first question.
But I also want to use this function as a normal js function. How do I pass on the data {name: "Namaskara"}?":
You would need to pass in an object with data property:
greet({data: {name: "Namaskara"}});
2). The second question about context:
var $kannada = $('#kannada'); // another button
greet.call($kannada[0], {data: {name: "Namaskara"}});
In this case greet will be invoked like if you manually clicked #kannada button, meaning that context this will be pointing to button#kannada. Of course in this case event object inside greet will not be real mouse event, but it will have data property properly set.
Demo: http://jsfiddle.net/ddhzwk43/
$('button').click(function(){
otherfunction('Namaskara');
});
function otherfunction(name){
//do something here with the name :)
alert(name);
}
http://jsfiddle.net/wzbphgyv/
Updated with your ID thing inside:
http://jsfiddle.net/wzbphgyv/1/
$('button').click(function(){
second_function('param_data1', 'param_data2');
});
function second_function(getParam1, getParam2){
alert(getParam1 + getParam2);
}
Fiddle code
No need for second function mapping use proxy instead:
function greet(name){
console.log(name);
}
var proxy = $.proxy(greet, this, "hello");
$("#test").on("click", proxy);
Another way is to use data-* html5 attribute to hold specific data to utilize. You can do something like this:
HTML:
<button data-name="Hello">click</button>
<button id="kannada" data-name="Namaskara">kannada</button>
jQuery:
function greet() {
alert($(this).data('name')); // alerts - Hello for button 1
} // alerts - kannada for button 2
$(function () {
$("button").on("click", greet);
});
Sample Demo

How to update cached jquery object after adding elements via AJAX

I'm trying to write a plugin-like function in jQuery to add elements to a container with AJAX.
It looks like this:
$.fn.cacheload = function(index) {
var $this = $(this);
$.get("cache.php", {{ id: index }).done(function(data) {
// cache.php returns <div class='entry'>Content</div> ...
$(data).insertAfter($this.last());
});
}
and I would like to use it like this:
var entries = $("div.entry"),
id = 28;
entries.cacheload(id);
Think that this would load another "entry"-container and add it to the DOM.
This is works so far. But of course the variable that holds the cached jQuery object (entries) isn't updated. So if there were two divs in the beginning and you would add another with this function it would show in the DOM, but entries would still reference the original two divs only.
I know you can't use the return value of get because the AJAX-call is asynchronous. But is there any way to update the cached object so it contains the elements loaded via AJAX as well?
I know I could do it like this and re-query after inserting:
$.get("cache.php", {{ id: num }).done(function(data) {
$(data).insertAfter($this.last());
entries = $("div.entry");
});
but for this I would have to reference the variable holding the cached objects directly.
Is there any way around this so the function is self-contained?
I tried re-assigning $(this), but got an error. .add() doesn't update the cached object, it creates a new (temporary) object.
Thanks a lot!
// UPDATE:
John S gave a really good answer below. However, I ended up realizing that for me something else would actually work better.
Now the plugin function inserts a blank element (synchronously) and when the AJAX call is complete the attributes of that element are updated. That also ensures that elements are loaded in the correct order. For anyone stumbling over this, here is a JSFiddle: http://jsfiddle.net/JZsLt/2/
As you said yourself, the ajax call is asynchronous. Therefore, your plugin is asynchronous as as well. There's no way for your plugin to add the new elements to the jQuery object until the ajax call returns. Plus, as you discovered, you can't really add to the original jQuery object, you can only create a new jQuery object.
What you can do is have the plugin take a callback function as a second parameter. The callback could be passed a jQuery object that contains the original elements plus the newly inserted ones.
$.fn.cacheload = function(index, callback) {
var $this = this;
$.get('cache.php', { id: index }).done(function(html) {
var $elements = $(html);
$this.last().after($elements);
if (callback) {
callback.call($this, $this.add($elements));
}
});
return $this;
};
Then you could call:
entries.cacheload(id, function($newEntries) { doSomething($newEntries); } );
Of course, you could do this:
entries.cacheload(id, function($newEntries) { entries = $newEntries; } );
But entries will not be changed until the ajax call returns, so I don't see much value in it.
BTW: this inside a plugin refers to a jQuery object, so there's no need to call $(this).

Javascript, passing a variable into a click event?

I really can't figure out how I would do this. It's more of a concept question than a code question so I'll just post an example:
object = $('#div');
function doSomething(object) {
//iterates through a list and creates a UL with items in corresponding to that list.
$(body).append("<li id='clickme'>Hello world</li>");
}
function createModal(object) {
//creates modal dialogue.
doSomething(object);
//more stuff
}
$('#clickme').live("click", function() {
//I need access to object (not the object declared at first,
//the object passed into doSomething) here.
});
Any ideas how I would do such a thing? doSomething would create a set of LIs and have a parameter passed into it. When those LIs the function creates are clicked, they need to interact with the parameter that's passed into doSomething. Is there a way to bind them or something?
Sorry if I didn't make any sense.
You can use jquery data function to associate data to your DOM elements. You then can read those data when handling events.
An alternate way, generally not recommended but useful when you build your html in one big pass and don't have an easy access to the DOM elements, and only have strings (or keys), is to add an attribute and retrieve it later using jquery's attr function. Whenever possible I recommend you to use the data function though.
Store the reference explicitly:
function doSomething(object) {
//iterates through a list and creates a UL with items in corresponding to that list.
$(body).append(
$("<li/>", { id: 'clickme', text: 'Hello world',})
.data('object', object)
);
}
Then the event handler can retrieve the reference:
$('#clickme').live("click", function() {
var object = $(this).data('object');
// ...
});
Also .live() is deprecated:
$('body').on('click', '#clickme', function() {
is the hip new way to bind delegated event handlers.
object = $('#div');
function doSomething(object) {
$(body).append("<li id='clickme'>Hello world</li>");
$('#clickme').click(function(evt) {
// Here you have access to `object`
});
}
function createModal(object) {
//creates modal dialogue.
doSomething(object);
//more stuff
}
This might not be enough. If you are creating multiple links rather than just the single one with id clickme you might have to find a different selector to use when you attach the click-handler. But if you nest the function that way, you have access to the parameter object that was used when the click-handler was created.
Another option would be to declare and attach the handler in a location where the parameter would be in scope, through closures (not tested):
function doSomething(object) {
$(body).append("<li id='clickme'>Hello world</li>").click(function() {
//object is accessible here
});
}

Can't access page-wide javascript variable

I'm fetching a JSON response and with that response, I have two values:
Air shipment cost.
Land shipment cost.
I want to save those two values somewhere in the client so that when a user chooses either 1 radio button or the other, I add that value to another element on the page.
Here's what I'm doing:
<script type="text/javascript">
$(document).ready(function () {
var landCost;
var airCost;
$("#ddlCiudad").change(function () {
var idCity = $("#ddlCiudad").val();
$.getJSON("/ProductCheckout/GetPriceForLocation", { cityId: idCity, productId: idProduct, type: "land" },
function (cityData) {
console.log("Recieved json data."); //This part works. It outputs.
var data = $.parseJSON(cityData);
console.log("Parse JSON response."); //This part works. It outputs.
landCost = data.LandCost;
console.log("Assigned value of LandCost"); //FAILS HERE. nothing is shown. not even an error.
airCost = data.AirCost;
console.log("Assigned value of AirCost");
alert(landCost);
console.log("Alerted land!");
alert(airCost);
console.log("Alerted air!");
}
);
});
So what do you suggest? I need to have the values of this JSON response, available for usage on that page, if I declare the variable inside the change() event, it'll be out of scope.
{"DaysToShip":" TER = 48 Hrs / AER = 24 Hrs","LandCost":"25,00","AirCost":""}
try
landCost = cityData.LandCost;
If you really must use global variables, you can attach them directly to the window object.
window.airCost = cityData.AirCost;
Really though you want to have the json request and the 'radio button' handling in the same scope, so that you're not polluting the global namespace at all.
Your call to $.parseJSON() is returning null because the data passed to your callback has already been parsed to JSON.
var json = {LandCost:3, AirCost:5},
results = $.parseJSON(json);
console.log(results); // results == null
IF you want to globally declare your variables, either put them outside the jQuery closure ($(document).ready(function () {...});), or don't use var to declare them. If you don't use the var keyword the variable will default to a global.
Here is a jsfiddle of setting global variables without using the var keyword: http://jsfiddle.net/jasper/JWtbV/
Have you considered using jQuery's $.data() function to attached the values directly to the body element in the DOM and accessing it from there?
// Set Values
$('body').data('landCost', data.LandCost);
$('body').data('airCost', data.AirCost);
// Retrieve Values //
console.log($('body').data('landCost');
console.log($('body').data('airCost');
Hope it helps.

Categories