document.getElementById doesn’t work - javascript

If I write code 2 without code 1, the code works and it shows me “aaaaa”.
But if I write code 1 and code 2, the code doesn’t work. Instead of showing me “vvvaa”, it doesn’t show me anything (not “aaaaa” and not “vvvaa”).
Why doesn’t it work? (The document.getElementById doesn’t send the information to the <div>.)
Code 1:
document.getElementById('na').innerHTML = "vvvaa";
Code 2:
document.write("<div id='na'> aaaaa </div>");
Complete Code: (the only thing on the page)
<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
timeago('1376743609');
document.write("<div id='na'> aaaaa </div>");
</script>

Order matters. You cannot access your element 'na' before having it in the document.
You naturally need to add the element to the document first. If that's done, you can access it by functions like getElementById().
This...
document.write("<div id='na'></div>");
document.getElementById('na').innerHTML = "vvvaa";
... will work.
You may shortcut this to:
document.write("<div id='na'>vvvaa</div>");

I am assuming your console says that document.getElementById('na') is undefined and innerHTML is not a method of undefined. This is caused by the fact that there is no such element when the code is called. A fatal error will stop any further javascript execution, in this case your document.write.
Add the element to your document first before trying to access it via document.getElementById

You can't access a piece of text unless it really does exist. In your case, you are trying to access the text when it doesn't even exist at that point. The order matters. Code 2 should go first and Code 1 should go last. First write the text, then access it.

The document.write only be passed after timeago() therefore does not exist over the <div>, so just call "timerago" after using document.write Try:
<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
document.write("<div id='na'> aaaaa </div>");
timeago('1376743609');
</script>

Related

JavaScript - Document write call being skipped

Writing a JavaScript function to print 'Computing', perform whatever, then print the answer to the same area
function compute() {
document.getElementById('solution').innerHTML = 'Computing'
.
.
document.getElementById('solution').innerHTML = 'Answer: ' + x
}
My problem is that no matter how much time is elapsed, it never seems to actually print 'Computing' and only prints the Answer. What method should I use to ensure that the first document change is applied and not ignored?
It's because you set the innerHTML to Computing, then immediately overwrite it. You can append the new text with solution in a new line like so:
function compute() {
document.getElementById('solution').innerHTML = 'Computing';
document.getElementById('solution').innerHTML += '<br>Answer: ' + x
}

Javascript ID Extracted From String Not Working

Here's the situation:
function STP() { var LOC = window.location.href;
var CSV = LOC.substring(LOC.indexOf(',')+1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length -1 ];
var POS = window.document.getElementById(STR).offsetTop;
alert( STR ); };
Explained:
When the page loads, the onload calls the script.
The script gets the location.href and Extracts the element ID by
creating an array and referencing the last one.
So far so good.
I then use that to reference an element ID to get its position.
But it doesn't work.
The STR alert indicates the proper value when it's placed above POS, not below. The script doesn't work at all below that point when the STR var reference is used.
However if I do a direct reference to the ID ('A01') no problem.
Why does one work and not the other when both values are identical? I've tried other ways like using a hash instead of a comma and can extract the value that with .location.hash, but it doesn't work either.
The problem is that when you do
LOC.substring(LOC.indexOf(',') + 1);
you're putting everything after the , into the CSV variable. But there is a space between the comma and the 'A01'. So, the interpreter reduces it to:
var POS = window.document.getElementById(' A01').offsetTop;
But your ID is 'A01', not ' A01', so the selector fails.
function STP() {
var LOC = 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810, A01';
var CSV = LOC.substring(LOC.indexOf(',') + 1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length - 1];
console.log(`'${STR}'`);
}
STP();
To solve this, you can increase the index by one:
LOC.substring(LOC.indexOf(',') + 2);
But it would probably be better not to put spaces in URLs when not necessary - if possible, send the user to 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810,A01' instead.

d3.format thousand separator on variables?

Hello I'm yet again stuck on d3...
I'd like to know how to use a thousand seperator on a variable all the examples I've managed to find seem to be on static data.
This is what I've tried so far:
d3.csv("OrderValueToday.csv", function(obj) {
var text = 'Today = £';
var totalSales = text + d3.format(",") + obj[0].Today;
svgLabel = d3.select("#label").append("h2")
.text (totalSales);
});
However it just outputs a load a stuff on the webpage this is it:
Today = £function (n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):a; if(0>p){var c=Zo.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x=n.lastIndexOf("."),M=0>x?n:n.substring(0,x),_=0>x?"":t+n.substring(x+1);!s&&f&&(M=i(M));var b=v.length+M.length+_.length+(y?0:u.length),w=l>b?new Array(b=l-b+1).join(r):"";return y&&(M=i(w+M)),u+=v,n=M+_,("<"===o?u+n+w:">"===o?w+u+n:"^"===o?w.substring(0,b>>=1)+u+n+w.substring(b):u+(y?n:w+n))+e}20000
So all I want is to be able to make the totalSales value have thousand separators so like 20,000 everything else I've tried doesnt do anything. I've read this https://github.com/mbostock/d3/wiki/Formatting but didnt see what I could do for my scenario.
Any help would be greatly appreciated. Cheers
Specifying a d3.format returns a formatting function, which you must then call as a function, passing in the number to be formatted as an argument:
var myNumber = 22400;
d3.format(',')(myNumber); // returns '22,400'
Sometimes you will see a format function stored as a variable like this:
var commaFormat = d3.format(',');
commaFormat(1234567); // returns '1,234,567'
In your case, you could do the following:
var totalSales = text + d3.format(',')(obj[0].Today);

How to fix Javascript NaN issue?

Here is my code
var total_center_buttons=$('.center_button').length;
var center_button_height=$('.center_button:first-child').height();
var total_center_button_height=total_center_buttons + center_button_height;
alert(total_center_button_height);
Here total_center_button value =3
and center_button_height is 40 while alerting them separately.It returns NaN. I tried ParseInt also but result is same.Please suggest me the solution.Thanks in advance.
Krishna
We have to guess, since you haven't quoted the DOM, but my guess is that $('.center_button:first-child') doesn't match any elements. Calling height() on an empty set returns undefined. When you try to add it to the number from the previous line, you get NaN.
I suspect you didn't want :first-child, but rather
var center_button_height=$('.center_button').first().height();
...but again without seeing the DOM, it's hard to say. To avoid repeated DOM lookups, you'd do this:
var buttons = $('.center_button');
var total_center_buttons = buttons.length;
var center_button_height = buttons.first().height();
var total_center_button_height = total_center_buttons + center_button_height;
alert(total_center_button_height);
.center_button:first-child will only match an element that both has the class center_button and is the first child of its parent element. My suggestion above is based on the assumption that you really wanted the first of the buttons, and that the buttons aren't the first thing in their parent.
Finally: That + in
var total_center_button_height = total_center_buttons + center_button_height;
looks suspicious. Again without seeing the markup it's hard to say, but you may have meant * there.
Mate,
there's a typo in your post. Notice the code line where you assign the value to total_center_button_height
var total_center_button_height = center_button_height + total_center_button_height;
That's where the problem is, the variable to the right of the addition operation (total_center_button_height) does not exist yet. Replace that line with...
var total_center_button_height = center_button_height + total_center_buttons;
Pretty straight forward
Hope it helps
Leo
may be you need to write this
var total_center_button_height=center_button_height + total_center_buttons;
alert(total_center_button_height);
you can check for "isNaN" function, this is to check whether the parameter is number or not.
Try this:
$(function(){
var total_center_buttons = $('.center_button').length > 0 ? $('.center_button').length : 0;
if(total_center_buttons !=0){
var center_button_height=$('.center_button:first-child').height();
var total_center_button_height = center_button_height + total_center_button_height;
alert(total_center_button_height);
}
});
you are doing this:
var total_center_button_height=center_button_height + total_center_button_height;
i.e. total_center_button_height is used in the same line where it is declared. At this time it is undefined.
i guess, you should be doing:
var total_center_button_height=center_button_height + total_center_buttons;
Try something like this:
var total_center_buttons=$('.center_button').length;
if (typeof total_center_buttons != 'undefined') {
var center_button_height=$('.center_button:first-child').height();
var total_center_button_height=total_center_buttons + center_button_height;
alert(total_center_button_height);
}

javascript timed function - expected identifier

I am having a problem with a simple script that is supposed to update a page with some values(user input) that are turned from monthly to yearly (the numbers go into numeric fields created by confirmIT)
<script>
function update() {
for (var i = 0; i < 9; i++) {
var ans = parseInt(document.getElementById("bq10a_" + i).value, 10);
if (!isNaN(ans)) {
var new = ans * 12;
document.getElementById("bq10a_" + i + "calc").value = new;
}
}
}
return;
}
setInterval("update()", 1000);
</script>
this yields an Expected identifier error on line
var new = ans*12;
and i would appreciate any help on how to solve it
The word new is a reserved word in JavaScript and cannot be used as the name of a variable.
The error means that the parser expected an "identifier", which is to say that it expected to see a valid identifier.
Change the name of the variable and things should improve. In the code you've posted I think there's a { } nesting problem; there appears to be one too many before the return of the function.
edit — also as jbabey notes in a comment, your setInterval() call should be
setInterval(update, 1000);
It's not a good idea, generally, to pass strings to setInterval(), despite the advice of thousands of mouldy old instructional websites.
Word "new" -- is special in javascript language:
line is incorrect:
var new = ans*12;
try this:
var newvalue = ans*12;
More information on:
http://javascript.about.com/library/blreserved.htm
http://www.ecma-international.org/publications/standards/Ecma-262.htm

Categories