Hyphen in div id causing javascript error - javascript

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

Related

how to console.log html tag attribute's value with hyphen in the middle in JavaScript?

I would need some help about this attribute:
<script id="mysdk" src="https://www.myscript.com/sdk/js?currency=EUR" this-client-token="nsiYXV0aG9yaXphdGlvbkZpbmdlcnByaW50IjoiZGUyYjM4N2FiZWV"></script>
What I'm trying to do is to console.log this-client-token in this way:
var el = document.getElementById("mysdk");
console.log(el.this-client-token);
This because, after making this work, I will be finally able to change the value of this-client-token, since that is my purpose. But I get the following error in the console:
Uncaught ReferenceError: client is not defined
I have no idea why I get this error, is it because of the hyphen? any suggestion?
Thank you!
Elliot
It doesn't work because - is subtraction. It's trying to calculate el.this - client - token, which fails because none of these variables exist.
Change to a data-XXX attribute, and use the dataset property.
var el = document.getElementById("mysdk");
console.log(el.dataset.clientToken);
<script id="mysdk" src="https://www.myscript.com/sdk/js?currency=EUR" data-client-token="nsiYXV0aG9yaXphdGlvbkZpbmdlcnByaW50IjoiZGUyYjM4N2FiZWV"></script>
If you can't change the attribute (because it's required by the SDK script, which you can't change) you can use el.getAttribute("this-client-token")

Can't get text into variable from XML files using javascript

I have been banging my head over this (probably simple) issue and am missing something really basic. Why does this first code display the expected output
xmlhttp=xmlhttp.responseXML;
document.getElementById("CenterDataBox").innerHTML= xmlhttp.getElementsByTagName("ShowDay")[0].childNodes[0].nodeValue;
and this second one doesn't? I think this is something really simple I've overlooking.
xmlhttp=xmlhttp.responseXML;
var DayOfShow = xmlhttp.getElementsByTagName("ShowDay")[0].childNodes[0].nodeValue;
document.getElementById("CenterDataBox").innerHTML= DayofShow;
The error is that your variable DayOfShow is not what you're using. You're using DayofShow, without capital '0' letter.
JavaScript is case-sensitive.
= DayofShow should be = DayOfShow in example 2.
You got mispelling of set variable. In example 2 i assume you're getting error var not defined. That is because you set value to DayOfShow and below you set inner html to DayofShow. Javascript is case sensitive.
Here you can read more about JS.

Why does JavaScript display 01002004 as 6295553?

I have the codes below:
<script type="javascript">
var item = 001002004;
alert(item);
</script>
Whenever I see this page in view source in my web browser, I see these lines of code exactly as same as here. But when alert() function runs, I see an unknown message. It alrest '6295553'. I don't know where is this unknown value from. I'm sure anything don't happen to item and it did not change before of alert.
What do you think ? What's the problem ?
Any number prefixed with 0 will be considered as octal. and 0x for hexa decimal
I am guessing that you are having it as an numeric value like below or using parseInt function to parse the string and when you alert it you see a different value..
var item = 001002004;
alert(item);
Or probably you are doing something like below
var item = '001002004';
alert(parseInt(item));
See more details on parseInt #MDN
DEMO HERE
Try changing the script type to "text/javascript" <script type="text/javascript">, or don't use the type attribute at all. See this jsfiddle
http://jsfiddle.net/3jK2v/
Please have a look at above fiddle. It does not alert anything anomalous for me.
are you sure you are not changing the variable -- maybe with a cap. eg
var item = 'some value';
alert(Item);

javascript code error shows undefined value

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/

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