javascript code error shows undefined value - javascript

function abc(id, name){
var button = '<img src="/images/abc.png" onclick="getvalue('+id+','+name+')"/>';
$('Div1').set('html',button);
}
my this code is not working. it gives an error.
The error is: suppose value of name is Gaurav. then it gives error Gaurav is not defined.
Please help me and tell me where is error.

That is because you are generating code that uses the string value without delimiters.
If id is 42 and name is Gaurav, you will generate the code getvalue(42,Gaurav) instead of getvalue(42,'Gaurav').
Put apostrophes around the string in the code:
var button = '<img src="/images/abc.png" onclick="getvalue('+id+',\''+name+'\')"/>';
Note that this only works as long as the string values doesn't contain any characters that need encoding, like apostrophes or auotation marks.

You need quotes around name and id.
var button = '<img src="/images/abc.png" onclick="getvalue(\''+id+'\',\''+name+'\')"/>';

You need to enclose the function arguments in quotes:
var button = '<img src="/images/abc.png" onclick="getvalue('+id+',\''+name+'\')"/>';
By omitting the quotes, you are passing the undefined variable Gaurav in as an argument to the function. What you really intend is to pass in the string "Gaurav" rather than a variable.
Quotes around id may also be necessary:
var button = '<img src="/images/abc.png" onclick="getvalue(\''+id+'\',\''+name+'\')"/>';

The error likely occurs on the call to getvalue as you are supplanting the value of name and not passing a reference. In essence when the code is emitted it would read...
<img src="/images/abc.png" onclick="getvalue(something, Gaurav)" />
Which will cause a problem for the javascript engine as it has no idea what Gaurav is.. try quoting the value..
var button = '<img src="/images/abc.png" onclick="getvalue(\''+id+'\',\''+name+'\')"/>'
Which will render something to the effect of..
<img src="/images/abc.png" onclick="getvalue('something', 'Gaurav')" />

You should mention what the intent of the code is, as it's not completely clear. I'm guessing that it takes the id and name, and dynamically creates an image. I'm not sure if you're using jQuery or not, since I see the use of "$".
Setting the click handler in this way, with string concatenation, is not as safe as doing it programatically. You can easily run into code injection issues with your original approach. e.g. if the name has the word "O'Reilly" in it.
If you're using jQuery, you can do something like this:
var button = $('<img src="...">').click(function() { getvalue(id, name); });
You can find more examples here: http://api.jquery.com/click/

Related

Setting an element value using HTML entities

I'm having an issue trying to set an input field's value when using HTML entities in that they are coming out literally as " rather than ".
Here is the code I am using:
document.getElementById('inputSurname').setAttribute('value', 'test"""');
in which the output is test""" though I want the output to be test""".
It doesn't look like a double-encoding issue since in the source code I am seeing it the same way I have set it here.
I know I could decode the value from its HTML entity format though this is something I want to avoid if possible for security.
Any help would be much appreciated :)
Try this:
document.getElementById('inputSurname').value = 'test"""';
Or if you want to keep &quot:
function myFunction() {
document.getElementById('myText').value = replaceQuot('test&quot&quot&quot');
}
function replaceQuot(string){
return string.replace('&quot', '""');
}
Or you can use escape characters.
document.getElementById("inputSurname").setAttribute("value", "test\"\"\"\"");
Well you could just write the new value as 'test"""'.
For other characters however, I'm going to refer you to this answer: HTML Entity Decode

JavaScript escape from multiple quotes

I'm basically trying to put this.name instead of "main" tag. Could not find a way to do it on javascript since quotes messes it up.
Code:
document.querySelector('button[name="main"]').classList.add('selected');
try :
document.querySelector('button[name='+this.name+']').classList.add('selected');
Just check
var obj = document.querySelector('button[name="main"]');
alert(obj);
It is working, the problem is in you classlist.add('selected') part

How to pass a String variable containing value with hyphens as a java script function parameter

Hi I am a newbie to java script. Have issues in passing the string variable whose value contains hyphen as function parameter. Fire bug throws an error saying 'identifier starts immediately after numeric literal'
I am using flexigrid to display data. In each row have placed an image. On click of that image a java script function should be called. Setting up of flexigrid record content is done in java as below,
record.put("view","<img src='images/ic_text_document.png' onclick='view_content("+objid+")'/> ");
Value of the varible objid is something like this c2692d22-a407-4d38-85ee-5c16f25bcce7.
Firebug throws identifier starts immediately after numeric literal' error by pointing at the 14th digit (in the above example at 4).
Tried passing the variable with different combination of quotes as suggested in other posts but dint work. Can somebody help me with this?
You'll need to escape the objid before generating the html, and unescape when using the value in the javascript.
OR do something like this......
record.put("view","<img src='images/ic_text_document.png' onclick='view_content("+ COUNTER + ")'/><div style='display:none' id='objid"+ COUNTER + "'>" + objid + "</div> ");
where counter is just a different number/value for each obj/objid.
and in js:
function view_content(objidcounter){
var real_objid = document.getElementById('objid' + objidcounter).innerText;
...
...
}
You should quote the objid value, like
record.put("view","<img src='images/ic_text_document.png' onclick='view_content(\""+objid+"\")'/> ");
Because when it render it is showing up as
view_content(FOOBARSTRING)
You need quotes in there.
record.put("view","<img src='images/ic_text_document.png' onclick='view_content(\""+objid+"\")'/> ");
Ideally you would not be adding the onclick handlers in the html markup directly.

Hyphen in div id causing javascript error

I'm having an issue with javascript whereby i am performing the following to close a popup window and update a field in the parent window with the required value. Code looks something like this:
<script language="javascript" type="text/javascript">
var FieldID = document.form.field22-1.value;
self.parent.opener.document.+FieldID = 'some text';
window.top.window.close();
</script>
However I am getting the following error:
Error: missing ; before statement
I have a funny feeling the javascript is interpreting the field id (field22-1) as having a subtraction in it. Which I guess would make sense. Any ideas/help would be ridiculously appreciated, really don't want to have to go back in and change the - in the code!
Thanks in advance!
Use document.getElementById('field22-1').value instead.
You might also need to fix this:
self.parent.opener.document[FieldID] = 'some text';
In JavaScript, any property of any object can be accessed either via dot notation, e.g. foo.bar, or bracket notation, e.g. foo["bar"]. The latter is necessary when your property is not a legal identifier (as in your case):
var FieldID = document.form["field22-1"].value;
Alternatively, if this is an actual id attribute, you should use:
var FieldID = document.getElementById('field22-1').value;
You could also use document.form['field22-1'].value.
You can use document.getElementById('field22-1').value

Escaping dilemma in Javascript

I have the following
var id='123';
newDiv.innerHTML = "";
Which renders in my HTML.
The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown...
notice how the TestFunction is a string here (it is executed within StepTwo using eval).
I have tried to format my JS as by :
newDiv.innerHTML = "";
but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief.
Would appreciate if anyone could point me in the right direction. Thanks!
One of the biggest capital failures on the internet is creating html in javascript by gluing strings together.
var mya = document.createElement("a");
mya.href="#";
mya.onclick = function(){
StepTwo(function(){
TestFunction('123', false );
}, true );
};
newDiv.innerHTML = "";
newDiv.appendChild(mya);
This Eliminates the need for any fancy escaping stuff.
( I probably should do 'onclick' differently, but this should work, I'm trying hard not to just use jQuery code to do everything )
Heres how I would do it in jQuery:
jQuery(function($){
var container = $("#container");
var link = document.createElement("a"); /* faster than $("<a></a>"); */
$(link).attr("href", "Something ( or # )" );
$(link).click( function(){
var doStepTwo = function()
{
TestFunction('123', true );
};
StepTwo( doStepTwo, false ); /* StepTwo -> doStepTwo -> TestFunction() */
});
container.append(link);
});
There is no good excuse for gluing strings together in Javascript
All it does is ADD overhead of html parsing back into dom structures, and ADD potential for XSS based broken HTML. Even beloved google get this wrong in some of their advertising scripts and have caused epic failures in many cases I have seen ( and they don't want to know about it )
I don't understand Javascript is the only excuse, and it's NOT a good one.
Try using " instead of \"
newDiv.innerHTML = "<a href="#"...
You should be using " not " or \" inside an HTML string quoted with double-quotes.
NewDiv.innerHTML = "";
There's probably a better way to do this - any time you find yourself using eval() you should stand back and look for a different solution.
You claim that eval is the right thing to do here. I'm not so sure.
Have you considered this approach:
and in your StepTwo function
function StepTwo(func,args,flag){
//do what ever you do with the flag
//instead of eval use the function.apply to call the function.
func.apply(args);
}
You could create the a element and attach to the click event using DOM Methods.
A Javascript Framework (like the ubiquitous jQuery) would make this a lot easier.
Your biggest problem is using eval, it leads to so many potential problems that it's nearly always better to find an alternative solution.
Your immediate problem is that what you really have is
as the next " after the start of the onclick attribute, closes it. Use " as others have suggested. And don't use eval.
You need to alternate your " and '.
Maybe you don't need quotes around the 123, because of Javascripts flexible typing. Pass it without quotes but treat it as a string within TestFunction.
Hey guys, thanks for all the answers. I find that the quot; seems to work best.
I'll give you guys some votes up once I get more reputation!
In regards to eval(), what you see in the question is a very small snapshot of the application being developed. I understand the woes of eval, however, this is one of those one in a million situations where it's the correct choice for the situation at hand.
It would be understood better if you could see what these functions do (have given them very generic names for stackoverflow).
Thanks again!
The best way is to create the element with document.createElement, but if you're not willing to, I guess you could do or use ".
In your code:
newDiv.innerHTML = "";
If it doesn't work, try changing "\'" to "\\'".
Remember that the " character is used to open and close the attribute on HTML tags. If you use it in the attribute's value, the browser will understand it as the close char.
Example:
<input type="text" value="foo"bar"> will end up being <input type="text" value="foo">.
...
I know this is hella' old now, but if anyone has issues with escaped strings when using eval (and you absolutely have to use eval), I've got a way to avoid problems.
var html = '';
eval('(function(div, html){div.innerHTML = html;})')(newDiv, html);
So, what's going on here?
eval creates a function that contains two parameters, div and html and returns it.
The function is immediately run with the parameters to the right of the eval function. This is basically like an IIFE.
In this case
var myNewMethod = eval('(function(div, html){div.innerHTML = html;})');
is basically the same as:
var myNewMethod = function(div, html){div.innerHTML = html;}
and then we're just doing this:
myNewMethod(newDiv, html); //where html had the string containing markup
I would suggest not using eval. If it can't be avoided, or if you control all the inputs and there's no risk of injection then this will help in cases where string escapes are an issue.
I also tend to use Function, but it isn't any more secure.
Here's the snippet I use:
var feval = function(code) {
return (new Function(code))();
}

Categories