Question

JavaScript

document.write(screen.width+'x'+screen.height);

var screenres='test';
document.write(screenres);
document.write('BBBBBBBBBBBBBBBBBBBBBBBBBBBB');

document.getElementById('resolutionfield').value = screenres;
document.write(screenres);
document.write('AAAAAAAAAAAAAAAAA');

I am trying to get the users screen resolution and pass it into an HTML post method. This snippet only prints out 1368x768testBBBBBBBBBBBBBBBBBBBBBBBBBBBB if I disable the document.getElementById line by adding two slashes in front of it, it prints everything out perfectly.

JavaScript

document.write(screen.width+'x'+screen.height);

var screenres='test';
document.write(screenres);
document.write('BBBBBBBBBBBBBBBBBBBBBBBBBBBB');

//document.getElementById('resolutionfield').value = screenres;
document.write(screenres);
document.write('AAAAAAAAAAAAAAAAA');

I am playing with this for the last 4 hours. It might be a simple problem but I just not able to figure it out.

Further down in my code

document.getElementById('secondsfield').value = seconds;
document.getElementById('minutesfield').value = minutes;
document.getElementById('hoursfield').value = hours;

these variables get passed on into the post method without any problems

HTML

<input type="hidden" id="usersipaddress" name="usersipaddress" value= "<?php echo $_SERVER['REMOTE_ADDR'];?>" >
<input type="hidden" id="secondsfield" name="secondsfield" value="" >
<input type="hidden" id="minutesfield" name="minutesfield" value="" >
<input type="hidden" id="hoursfield" name="hoursfield" value="" >
<input type="hidden" id="resolutionfield" name="resolutionfield" value="screenres" >

Anybody has the answer to this?

Was it helpful?

Solution

If this line:

document.getElementById('resolutionfield').value = screenres;

is executed too early before the resolutionfield DOM element has been parsed and thus is present in the DOM, then this will cause an error and stop execution of your script. That's because:

document.getElementById('resolutionfield')

will be null and then when you try to reference the .value property, it will not work and will generate the error Uncaught TypeError: Cannot set property 'value' of null which you can see in the browser's error console or debug console.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top