Pass variable to a javascript function in a c# code - javascript

I need to pass a variable to a javascript function,but I got a little trouble.
In the .cs file,I write like this:
string id = "someid";
this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction("+id+")\">"));
I need to use the value of this id,but in the console.log(id),it just shows "object",not the "someid",what's the problem?

Look at the generated HTML:
<input type="button" onClick="myFunction(someid)">
You are generating a variable name when you want a string literal.
Add some quote marks.
Whenever you have a problem that manifests in the browser: Look at the code the browser is dealing with first. You should always start by determining if the JS you want is not working or if the server side code is not generating the JS you want.

just add '' around id as i did below will resolve your issue
this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction('"+id+"')\">"));

Use the single quotes around id:
'"+id+"' (notice the single quotes then double quotes)

The problem is that it is looking for a saved variable on the page named someid, which is why you are getting the object in the console. Pranay Rana has a good solution which is to make sure the string someid is surrounded by single quotes.

Related

Adding JavaScript Function with arguments to an element from code behind

Hi Guys I've been dealing with an estrange thing while trying to pass string parameters to a JavaScript function from code behind, this is what I have actually in code behind which is wrong:
thumbnail = "<a href = 'javascript:RemovePirctureDetail(" + field1 + ",'" + tempname + "');' class='label label-default' rel='tooltip'>Remove</a>";
So this is the bad result I'm getting in the browser:
Remove
Meas that for some reason when I try to pass the string parameter, the html comes out bad formatted. The result should looks like this:
Remove
I tried already send the quotation marks like this /' from code behind, it did not work neither. How can I achieve this?
Thanks.
string thumbnail = "Remove";`
You need to use \ to escape the quotes inside, not /..
With javascript attribute I wouldn't use single quote, because it could be messy
Try to change in this way:
thumbnail = "Remove";
PS: Actually, I would NEVER use single quotes with attributes, it will cause an HTML validation error, HTML is not well formed with single quotes for attributes (although with inspection tools you see double quotes.. because inspection tools have the need to work with a well formed HTML, so if you want to see the real HTML of your page, view the source code (generally the option is on right-click on the page)

jQuery string escape onclick='deleteRow(item"+count+")' how to quote around item and count

I don't even know how to ask this question correctly, I tried to put quotes around a part of my string however it always break.
I am creating html dynamically and I am encountering error when I try to do this:
onclick='deleteRow("item"+count+"")'
I am trying to pass item1 as a string to a deleteRow function however best I could do is pass it like this deleteRow(item1) with no quotes. I am not sure how to escape them so that they would show.
This line of code is generated inside my JavaScript file.
I would recommend to use jQuery event handlers instead of inline one..
But in this case the below should do it
"onclick='deleteRow(\"item"+count + "\")'"

putting model variables inside js code

i have issues alternating js and razor syntax.
i am trying to pass the value of a model variable to a javascript function, let's say something like this
<script>
//this is my javascript function setTitle that simply changes the title
of a modal window, and i want to pass to it the title from the model
...
setTitle(#Model.titleName);
...
</script>
so when i do this it doesn't work, and the script seems to break.
If it's a string you have to surround it with quotes.
setTitle('#Model.titleName');
If it's an integer you obviously don't need that.
In situations like these it's helpful to Right Click -> View Source, and take a look at the javascript it generated, and also report any errors the console window showed when asking a question.
You need to encase the Razor code in quotes so the result is a JavaScript string
setTitle("#Model.titleName");

Pass multiple values with onClick in HTML link

Hi Im trying to pass multiple values with the HTML onclick function. Im using Javascript to create the Table
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
But in my Javascript function the userName is undefined and the valuationId is a string with the valuationId and the UserName combined
function ReAssign(valautionId, userName) {
valautionId;
userName;
}
If valuationId and user are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:
Re-Assign
If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:
<?php
echo 'Re-Assign';
?>
The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
The moral of the story is
'someString(\''+'otherString'+','+'yetAnotherString'+'\')'
Will get evaluated as:
someString('otherString,yetAnotherString');
Whereas you would need:
someString('otherString','yetAnotherString');
Solution: Pass multiple arguments with onclick for html generated in JS
For html generated in JS , do as below (we are using single quote as
string wrapper).
Each argument has to wrapped in a single quote else
all of yours argument will be considered as a single argument like
functionName('a,b') , now its a single argument with value a,b.
We have to use string escape character backslash() to close first argument
with single quote, give a separator comma in between and then start next argument with a
single quote. (This is the magic code to use '\',\'')
Example:
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
$Name= "'".$row['Name']."'";
$Val1= "'".$row['Val1']."'";
$Year= "'".$row['Year']."'";
$Month="'".$row['Month']."'";
echo '<button type="button" onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');" >submit</button>';
enclose each argument with backticks( ` )
example:
<button onclick="updateById(`id`, `name`)">update</button>
function updateById(id, name) {
alert(id + name );
...
}
Please try this
for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"
That is because you pass string to the function. Just remove quotes and pass real values:
Re-Assign
Guess the ReAssign function should return true or false.
A few things here...
If you want to call a function when the onclick event happens, you'll just want the function name plus the parameters.
Then if your parameters are a variable (which they look like they are), then you won't want quotes around them. Not only that, but if these are global variables, you'll want to add in "window." before that, because that's the object that holds all global variables.
Lastly, if these parameters aren't variables, you'll want to exclude the slashes to escape those characters. Since the value of onclick is wrapped by double quotes, single quotes won't be an issue. So your answer will look like this...
Re-Assign
There are a few extra things to note here, if you want more than a quick solution.
You looked like you were trying to use the + operator to combine strings in HTML. HTML is a scripting language, so when you're writing it, the whole thing is just a string itself. You can just skip these from now on, because it's not code your browser will be running (just a whole bunch of stuff, and anything that already exists is what has special meaning by the browser).
Next, you're using an anchor tag/link that doesn't actually take the user to another website, just runs some code. I'd use something else other than an anchor tag, with the appropriate CSS to format it to look the way you want. It really depends on the setting, but in many cases, a span tag will do. Give it a class (like class="runjs") and have a rule of CSS for that. To get it to imitate a link's behavior, use this:
.runjs {
cursor: pointer;
text-decoration: underline;
color: blue;
}
This lets you leave out the href attribute which you weren't using anyways.
Last, you probably want to use JavaScript to set the value of this link's onclick attribute instead of hand writing it. It keeps your page cleaner by keeping the code of your page separate from what the structure of your page. In your class, you could change all these links like this...
var links = document.getElementsByClassName('runjs');
for(var i = 0; i < links.length; i++)
links[i].onclick = function() { ReAssign('valuationId', window.user); };
While this won't work in some older browsers (because of the getElementsByClassName method), it's just three lines and does exactly what you're looking for. Each of these links has an anonymous function tied to them meaning they don't have any variable tied to them except that tag's onclick value. Plus if you wanted to, you could include more lines of code this way, all grouped up in one tidy location.
function ReAssign(valautionId, userName) {
var valautionId
var userName
alert(valautionId);
alert(userName);
}
Re-Assign

Javascript syntax to pass variables

Still muddling my way through Javascript, I'm trying to pass the contents of variable playnoyes to the long line of code below to decide whether or not to autoplay the flash movie, but doing it as I have below, the resultant line of code has the variable in quotes and therefore the code doesn't execute it as expected. My question is, how can I pass the variable so that the resulting line of code doesn't have the quotes around the variable value.
Many thanks, and sorry for the noobness of the question.
var playnoyes='true';
var testtext = "<script type='text\/javascript'>AC_FL_RunContent ('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay=\""+playnoyes+"\"&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer');<\/script>";
alert (testtext);
Thats because you are explicitly adding the quotes:
change
nigel&autoPlay=\""+playnoyes+"\"&autoRewind=true'
to
nigel&autoPlay=" + playnoyes + "&autoRewind=true'
Try this:
var playnoyes='true';
var testtext = "<script type='text\/javascript'>AC_FL_RunContent ('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay="+playnoyes+"&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer');<\/script>";
alert (testtext);
Remove the two '\"' on each side of the variable, no?

Categories

Resources