jquery append automatically decodes html encoded string - javascript

I have a string like this:
var b = "<button type='button' onclick='javascript:"+f+"(\""+ encodedString+"\");'> hi</button>"
//encodedString = "a " <hr> <br>"
and after I do something like:
$('li').append(b);
after this the encodedString becomes decoded and my onclick doesn't work because of the &quot becoming "

Instead of directly setting the click event through html, bind an event listener. eval(f) allows you to refer to functions by a string. If possible, I recommend passing a direct reference to the function.
If the function is defined in the global scope, use window[f]. Note: This won't work if f looks like Math.round, because window["Math.round"] != window["Math"]["round"].
//f is a string which contains a single function name.
var b = $('<button>').click(function(){
eval(f)(encodedString);
});
$('li').append(b);
If f is a dynamic variable, which changes (eg, in a loop), wrap the code in an anonymous function:
(function(f){
var b = $('<button>').click(function(){
f(encodedString);
});
$('li').append(b);
})(eval(f));

Related

Javascript remove double quotes in from object's value

I'm generating a JavaScript object in a Java class for use in javascript the result looks like this:
var gridDefinition = {"width":"100%",
"height":700,
"sortable":true,
"columns"[{"datafield":"id","datatype":"string","width":300,"hidden":true,"text":"ID"},
{"datafield":"lastname","datatype":"string","cellsrenderer":"renderer_openEntry","width":300,"text":"Nachname"},
{"datafield":"firstname","datatype":"string","width":200,"text":"Vorname"},
{"datafield":"officePhoneNumber","datatype":"string","width":150,"text":"Telefon"},
{"datafield":"companyName","datatype":"string","width":300,"text":"Firma"},
{"datafield":"mailServer","datatype":"string","width":200,"text":"Mail-Server"},
{"datafield":"mailFile","datatype":"string","width":400,"text":"Mail-Datei"}]} ;
cellsrenderer is a callback function name. How can I remove the doublequotes surrounding renderer_link? The result line should look like this:
{"datafield":"lastname","datatype":"string","cellsrenderer":renderer_openEntry,"width":300,"text":"Nachname"},
How to "remove the quotes" is the wrong question to ask. At the moment the code is running, there are no quotes that can be removed.
What you need is a map that maps a name to a variable, e.g.
var myFunctions = {
renderer_openEntry: renderer_openEntry,
// other functions
};
and then process the object to update the values of all cellsrender proeprties to refer to the value from the map instead of the string:
gridDefinition.columns.forEachfunction(column) {
if (column.cellsrenderer) {
column.cellsrenderer = myFunctions[column.cellsrenderer];
}
});

Name undefined error

I am making a div and in its onclick function I am calling function Remove() to which I am passing its id and name. But when I use name in my remove function, an undefined error is thrown. For example, I call Remove(1,xyz) and then in the Remove function I am unable to access xyz; it's showing me xyz is not defined.
Here is my jQuery code which calls the Remove function:
$("#h2-"+id).append("<div id = 'c2-"+id+"' onclick = 'Remove("+id+","+name+")' class='clear_btn1'> </div>");
and here is my Remove function:
function Remove(i, name){
alert("I am deleting " +name);
var sender = "<?php echo $user_check?>";
var receiver = name;
console.log("Name is " +sender);
console.log("receiver is " +receiver);
}
The value of i is coming perfectly fine but I cannot access name in my function.
Change your code as below
$("#h2-"+id).append("<div id = 'c2-"+id+"' onclick = \"Remove("+id+",'"+name+"')\" class='clear_btn1'>sdfsdf sdfsdf</div>");
What is saved in onclick is actually Remove(id,name). This looks okay at first look, but...
Say id=10 and name="Mark".
You would be calling Remove(10,Mark), which is not what you want. Mark would be treated as a variable. You therefore need to put additional quotes enclosing name to treat it as a string.
You should, of course, escape the additional quotes you would add.
You need to call Remove(10,"Mark"). Notice the quotes.

Run function from string and parse variable?

Let's say I have an object with this markup:
var obj = {
cat: function(string, bool, NEEDTHIS) {
console.log(string, bool, NEEDTHIS);
}
}
Lets say I have the function, with it's variables as an attribute on a button which I have NO control over how it's generated. Example:
<button type="button" onclick="obj.cat('foo', true, 'dog');">PRINT</button>
I need to run this function on the button, but remove the attribute so that I can parse my own attribute.
So I'd strip the attribute 'onclick', store it in a string like so:
var function = "obj.cat('foo', true);";
surely there's a way to just add in another argument without literally altering the string.
I'm also stuck on how I could run the function as it is from the string.
is this possible?
use eval
var function = "obj.cat('foo', true);";
eval(function);

finding the class of .click function

i have a string objects of books which i have got from a JSON objects. This Book object has three Key value pairs, Title,Author and URL. I use a for loop to read each object and just put the title of the object as a button on the html page. But when the button is clicked i want the URL of the book to be alerted. As i read the objects i make Books objects and push it into an array for later use. but i am not able to Use .Click() method the URL is not right. Please see the code for better understanding. :-)
for (i = 0; i < 6; i++) //I know that there is only 65 Books..jsonString.books.lenght is not working.
{
var title = jsonString.books[i].title;
var classname = title.replace(/\s/g, "");
var author = jsonString.books[i].author;
var URL = jsonString.books[i].url;
var htmlString = '<div class="' + classname + '"><input type="button" value="' + title + '"></div>';
$(htmlString).appendTo(attachPoint).click(function () {
loadBook(URL);
});
OneBook = new Book(author, title, URL);
arr.push(OneBook);
}
attachpoint is a reference in the html file that i got from
var attachpoint=document.querySelector('.buttonAttachPoint');
So in the above code the URL that i get on clicking is always the last object in the jsonString. this is happening coz of the for loop. So is there a way i can get to class name of the Div that has onclick or the title of the button so that i can get the URL from the array of objects i created? Or is there an easier way. Also could any one point out why "jsonString.books.lenght" is not working? Thanks in advance.:-) all the help much appreciated. :-)
Creating a closure using an immediately invoked function expression should do the trick. Just replace this:
$(htmlString).appendTo(attachPoint).click(function () {
loadBook(URL);
});
with this:
(function(URL) {
$(htmlString).appendTo(attachPoint).click(function () {
loadBook(URL);
});
})(URL);
URL inside the scope of that anonymous function will have the value passed to it, which will be the correct value for that iteration of the for loop.
In ECMAScript, variables are scoped to their function, rather than any block.
The functions you are binding to click have a closure over URL in the context of the loop as a whole, not over URL in the context of the loop iteration.
This means that whenever any of the functions are invoked, URL will have the last value that the loop sets it to.
You need to freeze the value of URL for each loop. One way to do this is to have a function elsewhere that takes URL as an argument, and returns a function that closes over it, thus:
function getBookLoader(url) {
return function (){
loadBook(url);
};
}
You can then replace your ... .click line with the following:
$(htmlString).appendTo(attachPoint).click(getBookLoader(URL))
To answer the question in the title, the target property of an event contains the object to which the event was dispatched, and the currentTarget property contains the object whose listeners are currently being evaluated. currentTargetshould be the div in question.

Executing a function by name, passing an object as a parameter

Here's the problem - I know function by name (and that function has already been loaded form an external script), but I don't have an actual function object avail for me to call. Normally I would call eval(function_name + "(arg1, arg2)"), but in my case I need to pass an object to it, not a string.
Simple example:
var div = document.getElementById('myDiv')
var func = "function_name" -- this function expects a DOM element passed, not id
How do I execute this function?
Thanks!
Andrey
Never use eval, it´s evil (see only one letter difference)
You can simply do:
var div = document.getElementById('myDiv');
var result = window[function_name](div);
This is possible because functions are first class objects in javascript, so you can acces them as you could with anyother variable. Note that this will also work for functions that want strings or anything as paramter:
var result = window[another_function_name]("string1", [1, "an array"]);
You should be able to get the function object from the top-level window. E.g.
var name = "function_name";
var func = window[name];
func( blah );

Categories