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 + "\")'"
I'm trying to escape out of some apostrophe's in my JSON. I know it's not ideal but i append the data to the DOM and call it later in the code. At the moment i get an error whenever there is an ' in the data. I've tried using replace and encodeURI but just doesnt seem to work.
My code basically looks like:
var addItem = function (item, target){
var obj = $(item).data('obj');
var obj_string = JSON.stringify(obj);
target.append("<div data-obj='" + obj_string + "'> Added </div>
}
When i inspect the element it breaks when it gets to the apostrophe:
{"publisher":"EA","games":[{"game":"Dragon's"}]}
Looks like this in the element inspector:
{"publisher":"EA","games":[{"game":"Dragon" s"}]}
And everything that follows is broken. Any ideas how i escape it?
I've found lots of ways if it was pureply jquery but with it being in the html it seems to not work.
You can avoid the escaping and stringification© using .data() to set the obj to the element directly.
$('<div/>').data('obj', obj).text('Added').appendTo(target);
Just keep in mind with this method you won't get a data attribute on the actual element itself but the data will be there when you request it with .data.
You are concatenating your content with a string that already uses single quotes. The concatenated result will most likely be <div data-obj='Dragon's'> which is not what you want.
Either escape the single quote when concatenating it (not sure the entity won't be interpreted):
.append("<div data-obj='" + obj_string.replace("'", "‚") + "'> Added </div>");
Or safer, you can build your nodes with jQuery which will give you a native escaping for some performance penalty:
.append($("<div>Added</div>").data("obj", obj_string));
Rather than leaving yourself open to XSS, try:
var div = document.createElement('div');
div.appendChild(document.createTextNode("Added"));
div.setAttribute("data-obj",obj_string);
target.append(div);
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
Ok, I'm getting some data from an ajax call and need to store the value as a parameter to an onclick element via javascript.
Eg
output = "<a href = '#' onclick = 'deleteFileName('" + trim(splitString[i]) + "')'> delete File </a>";
This behaves strangely. When I inspect the element with chrome, the output looks like this
<a href="#" onclick="deleteFileName("0design mockup.xlsx')'> delete File </a>
It should obviously look like this
<a href = "#" onclick = "deleteFileName('0design mockup.xlsx')">
The parameter is a String so I need the quotes around it. This may not be the best way to do this, but why is it making the first two quotes double quotes and then the last two single quotes?
*This is a JSP server using ajax calls to gather information. The function "deleteFileName(fileNameIn)" is an ajax call. (I don't believe this is necessary information but you never know)
You can not use the same kinds of quotes for the value of onclick and for the function call. You need single quotes for one and double quotes for the other (where to put which should not matter). Otherwise you are closing the onclick attribute with the first single quote of the function call.
Example:
output = "<a href = '#' onclick = 'deleteFileName(\"" + trim(splitString[i]) + "\")'> delete File </a>";
Rather than inspecting the information, I suggest that you wget or curl the page directly (or use the browser's view-source function). These days I've found that many browsers present information subtly incorrectly in the inspector in their attempt to format everything nicely.
Removing the browser from the equation is a good first step, since that will show you exactly where the problem is occuring.
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.