Javascript pass variable in href onclick request - javascript

I know this is really basic javascript but for some reason, I can't seem to get my link's onclick function to work when passing a parameter.
I have tried escaping the quotes, adding different types of quotes and adding the raw variable as a string.
I have it working with the below but it says that "XYZ is undefined"
function renderLink(value, meta, record)
{
var type = record.data['name']; //value is XYZ
return '';
}
function getReport(type){
alert(type);
}

return '';
You need to escape the string:
return '';

If you look at the rendered HTML, you'll see the problem: Your getReport call looks like this:
getReport(XYZ);
I'm guessing you want quotes around that, so:
return '';
...which renders:
getReport('XYZ');
Live example
Somewhat more esoteric, but when you output an onclick attribute as part of HTML source, it is of course an HTML attribute, which means you can use character entities. So you could use the " entity:
return '';
Live example
I point this out not because I recommend it (I don't), but because it's useful to remember what's really going on in an onclick attribute. This is one of the reasons I would strongly recommend using a proper event handler (e.g., via addEventListener / attachEvent, or even just assigning to the a element's onclick property once it's been instantiated) instead.
It's important to note that this way of doing it is also very sensitive to the content of record.data['name']. For instance, consider what happens if instead of XYZ it's Tom's. The output of the first option above would be
getReport('Tom's');
...which is obviously a problem. Similarly, if there's a backslash in the text, it will be treated as an escape character on the result, etc., etc. — a bit of a minefield.
If you can possibly change your renderLink so it returns an actual instantiated a element rather than a string, that's what I'd do:
function createLink(value, meta, record)
{
var type = record.data['name']; // Grab value as of when we were called
var link = document.createElement('a');
link.href = "javascript:void(0);";
link.onclick = function() { // Or even better, addEventListener / attachEvent
getReport(type);
return false;
};
return link;
}
That creates the link and a closure that accesses type without turning it into text and back again. (Don't worry if you're unfamiliar with closures, closures are not complicated.)
Live example

getReport receives XYZ as a variable not as a string, you need to put that inside quotes:
return '';

Related

Function parameter evaluates to undefined

When dynamically creating an element of type select, there are two problems when setting the onclick method:
It is impossible to simply set the onclick with element.onclick="updateInput(this.articleIndex)";
This results in a final HTML tag where no onclick is shown at all.
When set by e.setAttribute("onclick","updateInput(this.articleIndex)");, it does appear in the final HTML. And the updateInput method does get called.
However the functionality seems to be broken, as the argument always evaluates to undefined
Here a simple example of my problems:
var selectElem = document.createElement("select");
selElem.id="articleSelector_"+this.articleIndex;
console.log("the index of the article is " + this.articleIndex);
selElem.setAttribute("onclick","updateInput(this.articleIndex);");
//selElem.onclick="updateInput(this.articleIndex)"; //this does not work
The log shows the correct number. Inside the updateInput method, the argument is of value undefined instead of the number previously shown in the log.
Try attaching handlers with pure Javascript, and not with HTML, without onclick = "... (which is as bad as eval).
The this in your script refers to the calling context of the function - what is it?
You might want:
element.addEventListener('click', () => {
updateInput(this.articleIndex);
});
(arrow functions retain the this of their surrounding scope)
it is impossible to simply set the onclick with element.onclick="updateInput(this.articleIndex)";
What that code does is it assigns the string "updateInput(this.articleIndex)" to the onclick which makes no sense and certainly not what you want.
Even if you remove the quotes:
element.onclick = updateInput(this.articleIndex);
It is still incorrect because it assigns the result of the updateInput() function to the onclick which is again not what you want.
You need to assign a function name to the onclick like this:
element.onclick = updateInput;
However, this doesn't allow you to pass a parameter as you wish. To do so, you need to use an anonymous function:
element.onclick = function() {
updateInput(this.articleIndex)
};
When set by e.setAttribute("onclick","updateInput(this.articleIndex)");, it does appear in the final HTML. And the updateInput method does get called.
This works because it sets the attribute onclick and it is a string type, so everything is correct. It is equivalent to using the anonymous function above. The only difference is this, which in this case refers to the element itself, while in the above code it depends on the context that the code appears in. That's why in this case the argument always evaluates to undefined because the select element doesn't have an articleIndex property.
The problem is the value of the context this when that element is clicked, the context this is not available anymore at that moment.
You have two ways to solve this problem:
You can use the function addEventListener to bind the event click, and bind the function/handler with the desired context this:
The function bind binds a specific context to a function.
selElem.addEventListener('click', updateInput.bind(this));
function updateInput() {
console.log(this.articleIndex);
}
As you need a specific value, you can use data attributes. That way, you don't need to worry about the context this.
selElem.dataset.articleIndex = this.articleIndex;
selElem.addEventListener('click', function() {
updateInput(this.dataset.articleIndex); // Here you can get that value.
});

appendChild of objects containing javascript attributes

i have this Javascript function
function webit(thumb){
webi = document.createElement("img");
webi.alt=thumb.id.replace("t", "");
webi.id = "w"+webi.alt;
webi.className = "web";
webi.src= thumb.src.replace("thm","web");
webi.height=233;
webi.onclick='alert()';
document.body.appendChild(webi);
}
which is supposed to embed a larger version of a thumbnail image the end of the document. It works fine except that any javascript function ( ie onXXX) stays resolutely null. This seems to be no matter which JS function i use and afaict any thing i try to set it to.
The above example uses
webi.onclick='alert()';
which fails leaving onclick null, though all the other statements succeed.
When in javascript the .onclick property expects a function not a string
webi.onclick=function(){ alert(); };
You could also use the addEventListener method to set an event handler
webi.addEventListener("click",function(){ alert(); });
There are two problems, you are giving quotes to alert & onclick requires a function that can be called after clicking on it, you should not call the assigned function.
webi.onclick=function(){alert()};
You might consider declaring webi as var. Without "var", you implicitly defined window.webi, and it will introduce memory leaks.
var webi = document.createElement("img");
In addition, jQuery is usually a better choice than raw js/browser API.

cannot pass string to function

I'm using javascript and I try to pass a string to a function , like so
//example string
var f="a";
//add button that sends the value of f to the function
document.getElementById("mydiv").innerHTML="<input type='button' id='myButton' value='Click here' onclick='gothere("+f+");'> ";
function gothere(a){
alert(a);
}
I never see the alert and in console I see a is not defined (refers to the f I guess?)
If i set the f var to be a number then I see the alert.
What am I missing?
Thanks in advance
EDIT
I was thinking maybe something like
var buttonnode= document.createElement('input');
document.getElementById("mydiv").appendChild(buttonnode);
buttonnode.onclick=gothere(f);
Wont work for the same reason?
When your HTML get's rendered, you get onclick='gothere(a);', but the actual a variable doesn't exist in this context, you want to pass the value of f, as a string, so you'll need to use onclick='gothere(\""+f+"\");'. Note the extra quotes inside the parens. This will render to onclick='gothere("a");' thus passing the string.
When using a number, it works, because calling onclick='gothere(5);' is valid, since a variable can't be named 5, and it passes the number.
Actually, you don't have an a in your code. You are using variable f to denote a. So using this would help you:
var f="a";
// write the remains of the code as they are..
function gothere(f) {
alert(f);
}
Now when you'll call the function, there will be an alert of a in the browser.
Also, try wrapping the content in "" double qoutes to let the code understand that this is a string not a character.
For onclick use
onclick='gothere(" + f + ")'
And now, its onto you to write the value. Maybe the issue is because you're not writing the value for the f.
Try inpecting the error. I am sure there won't be anything.
Or try using the attribute field and change it using jQuery.
How about fixing your code ? You are missing the quotes around the value denoted by variable F.
Hence, when variable F is parsed, the function becomes gothere(a) . while a is not a defined variable (but its a value) and hence the error.
Try this !
document.getElementById("mydiv").innerHTML="<input type='button' id='myButton' value='Click here' onclick='gothere(\""+f+"\");'> ";
The modified part is onclick='gothere(\""+f+"\");'> "
This should work for you !
function parameter string value image dynamically from JSON. Since item.product_image2 is a URL string, you need to put it in quotes when you call changeImage inside parameter.
My Function Onclick inside pass parameter.
items+='<img src='+item.product_image1+' id="saleDetailDivGetImg">';
items+="<img src="+item.product_image2+" onclick='changeImage(\""+item.product_image2+"\");'>";
My Function
<script type="text/javascript">
function changeImage(img)
{
document.getElementById("saleDetailDivGetImg").src=img;
alert(img);
}
</script>
You need to use single quotation marks for value arguments (see #Nis or #CDspace answer).
Better way to handling dynamic clicks or other events is event binding. See jQuery event binding for example.

Assignement of a variable inside a concatenation

I have a global variable var num_tab=1;, a function that creates a link a href :
function Addsomething()
{
$("#tout").html("<a style=\""+"margin-left:-20px;"+"\" onClick=\"eval(num_tab=2)\" href=\""+"#tab1"+"\" data-toggle=\""+"tab"+"\">SELECT</a>");
Bla,Bla..
$("#champ1").append('<li id=\"1\" class="champ" onclick="insertAtCaret("sousTab'+num_tab+'");" value=\"1\">1</li>');
}
What i want to do is to create a href that when clicked changes the value of the variable num_tab, but if you can see the href is inside a jquery html(), which makes me confused about how to assign a value to the variable. I almost tried everything: onClick=\"num_tab=2\",onClick=\""+num_tab+"=2\"
Actually i tried something: when i write onclick='num_tab=2;alert("+num_tab+");' i still get the initial value of num_tab, seems it's more like a problem of local and global variable and i can't figure out it yet.
Please don't use eval(). It's insecure and not the appropriate tool for this job. Just assign a function to the onclick:
$("#tout").html("<a onclick='set_num_tab(2)'">); //fill out the rest of this line
function set_num_tab(value) {
num_tab = value;
}
That should give you an idea of how to do it. btw there's no reason you can't use single quotes around an onclick like that.
Alternately, this would work:
$("#tout").html("<a onclick='num_tab=2'">);
But that's pretty messy. I try to avoid inline JavaScript.

Passing Variables Javascript

I am trying to pass a variable in javascript. I create a link in the following manner and everything seems to be working.
label.innerHTML = ' link';
However when I create the link in the following way where the link would also pass an associated object I get the following error from firebug -> "missing ] after element list"
label.innerHTML = ' link';
Is this an acceptable way to pass an object to a function. The problem is that I am creating this link within a function. The function creates links like this based upon an object that is passed to it. Therefore I cannot have this "object" as a global scope.
You are building the script by mashing together strings, as such you can only work with strings and object will be automatically stringified.
Use DOM instead.
var link = document.createElement('a');
link.href = "#"; // Have a more sensible fall back for status bar readers and middle clickers
link.appendChild(document.createTextNode(' link');
link.addEventListener('click',function () { show_box(this, object); },false);
label.appendChild(link);
… but use a library that abstracts away the non-standard event models that some browsers have.
What you're trying to do is pass the contents of object to output. Since it's an object, the string representation will be something like [object Object]. The output HTML would look like:
link
which is invalid. Don't try to concatenate the object, just pass it along as another argument to the function, like this. Or, better yet, use jQuery:
<!-- somewhere in the head, or at least after the object is defined -->
<script type="text/javascript">
$(function() {
$('#thelink').click(function() { show_box(this, object); });
});
</script>
...
link
If your object is simple variable like numeric or string variable than it will be Ok but if you are passing html object it will not work because it will be something like below.
link

Categories