cannot pass string to function - javascript

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.

Related

How to pass argument from onclick function?

I have created a table and populated it using jQuery. Now I would like to add a text such as when we click on it a function executes. I have used onclick and it worked fine, but I also need to send a few arguments to my function, how can I send arguments to the targeted function from onclick:
var dataHtml = '';
$.each(data, function (index, user) {
dataHtml+="<code onclick=show_popup(1,user['donner'][0])> Donner details</code>";
});
$("#t-data").html(dataHtml);
function show_popup(show=0, donner){
$(document).ready(function(){
var showModel=show;
if(showModel==`1`){
$(`#modal-default-admin`).modal(`show`);
}
});
But it shows a "user is not defined" error. User is defined and I also can access it.
The user is in fact not defined. The problem you are facing is that you are using HTML as a string, so you are providing onclick=show_popup(1,user['donner'][0]) as string. When jQuery "makes HTML" out of this string and you click on it, it calls show_popup with 1 and user['donner'][0] and the user here is undefined. It was only available inside the $.each loop, not outside of it.
The simplest fix is to pass the value directly and not trying to do it as a pointer.
onclick=show_popup(1,\""+ user['donner'][0] +"\")>
Like this, it will use the value of user['donner'][0] when creating the HTML.
Bonus point: You should wrap the onclick attribute with quotes:
dataHtml += "<code onclick='show_popup(1,\""+ user['donner'][0] +"\")'> Donner details</code>";
Just to make sure that for example a space in the value of user['donner'][0] doesn't break it again.

Quotes escapes to correctly pass parameter from HTML input value to a javascript function from a PHP echo

I have a simple PHP echo statement which displays a HTML input box. I want to pass the data in value field when using the setTimeout function. I can't seem to get the quote escapes correct. This is my code snippets.
//PHP code
echo "<input type='text' id='myId' value='myVal' onkeyup='setTimeout(\"myFunction(this.value)\", 1000);'>";
How do I correctly pass [this.value] as a parameter to my myFunction
//Javascript code
function myFunction(val){
alert(val);
}
Thanks in advance
-M
You don't need any quotes there. The Javascript code should look like this:
setTimeout(myFunction, 1000, this.value);
You pass myFunction as function object as the first argument; this will be called by setTimeout. setTimeout also accepts further arguments which it will pass to the callback, so that's where you pass this.value. Since this doesn't involve any quotes, you don't need to worry about them.

value is taken as parameter on function

im passing a value retrieved from an ajax call to a function like this way:
nuevaFila+='<td><input type="button" value="Agregar" onclick="AgregarSuvenir('+item.CODSUVENIR+');"></td></tr>';
and we i clicked the button it throws an undefinided "variable" but is not a variable, i just wanted to pass it as a string, and the value passed to the function is taken as a variable, i tried
onclick="AgregarSuvenir("'+item.CODSUVENIR+'") and onclick="AgregarSuvenir('+item.CODSUVENIR+""')
but this fails
someone help me how to pass the value as string and not be taken a a variable.
thanks is advance
This is a simple case of matching quotes. Because you use single quotes to delimit the string, you must add escaped quotes inside your function call in order for the inserted value to be treated like a string.
Here are two possible solutions that escape the quotations to allow for the parameter to the AgregarSuvenir function to be treated like a string:
nuevaFila+='<td><input type="button" value="Agregar" onclick="AgregarSuvenir(\''+item.CODSUVENIR+'\');"></td></tr>';
or:
nuevaFila+="<td><input type=\"button\" value=\"Agregar\" onclick=\"AgregarSuvenir('"+item.CODSUVENIR+"');\"></td></tr>";
found it!
it has to be formatted like stated on this post: pass string parameter in an onclick function
onclick="AgregarSuvenir(\''+item.CODSUVENIR+'\')

javascript variable?

I have this:
function OpenVote(id, stemme) {
var postThis = 'infoaboutvote.php?id='+id+'&stemme='+stemme;
}
and this:
<script type="text/javascript">
OpenVote(10, CripO);
</script>
Why have i done wrong? as you see i want 10 to be "id" and CripO to be "stemme"
"CripO" looks like a string to mea -- which means it should probably be surrounded by quotes :
<script type="text/javascript">
OpenVote(10, 'CripO');
</script>
Else, it might be a variable -- in which case you should ensure it is initialized before executing that portion of code.
Also, in your OpenVote function, you are assigning an URL to the postThis variable ; but this will not do anything else.
Especially, it will not send any kind of Ajax request : you need more code, if you want to send an Ajax request to that URL, and get a result.
Shouldnt it be OpenVote(10, 'CripO'); -- I mean with 'Cripo' within quotes?
What do you want the function to do? Using the var keyword here indicates that that variable should only exist inside the function. If you're trying to set the postThis variable outside the function, omit the var.

How to programmatically change an inputs onblur?

I am trying to change the value of the onblur attribute of a text input after the page has finished loading.
When I do the following, it simply fires the function:
ip.onblur = stopCalcUpInt(this,10);
When I do the following, I have success:
ip.onblur = function onblur(event){stopCalcUpInt(this,10);}
Unfortunately, the whole point of this is to be able to dynamically set the second parameter for stopCalcUpInt(). If I hard code a value for it... it works fine... but any attempts to pass varibles to this fails... instead of putting the value of the variable as the second param it just puts the plain text of the variable name itself. Here is ideally what I am TRYING to do:
ip.onblur = function onblur(event){stopCalcUpInt(this,this.value);}
In this example, when I alert the ip.onblur I get:
It depends what this is intended to refer to. In an event handler this refers to the element on which the event is being handled. If that's what you want then your code looks good as written; this will point to ip.
If you intend this to refer to the this from outside the event handler and not ip then try this:
var self = this;
ip.onblur = function(event) { stopCalcUpInt(self, self.value); };
The answer to getting this to work was super easy, yet not overly obvious. Instead of:
ip.onblur = function onblur(event){stopCalcUpInt(this,this.value);}
I did this:
ip.setAttribute('onblur','stopCalcUpInt(this,\'' + ip.value + '\');');
Works perfectly... no more banging my head against the wall! Yay!
ip.onblur = function() {stopCalcUpInt(this,this.value);}
ip.onblur is an event handler... i.e. it's a function
Now, when you alert a function, FF will show you the source code for that function (if it's user defined).
That is why you're seeing the plain text of the variable name.
For an event handler, this is the element that is currently handling the event. So, if you're setting the onblur handler of an input box, you will have access to the contents of that input box.
The code sample that you provided:
ip.onblur = function onblur(event){stopCalcUpInt(this,this.value);}
should work correctly. Try
ip.onblur = function onblur(event){alert(this.value); stopCalcUpInt(this,this.value);}
if you want to be sure
Is stopCalcUpInt expecting a number in the second parameter? The value attribute will return a String, while in your hardcoded example you're passing a number type. Try this:
ip.onblur = function onblur(event){stopCalcUpInt(this,this.value * 1);}
As explained in QuirksMode:
Since multiplying assumes numbers,
JavaScript makes the string a number,
if possible.

Categories