<!DOCTYPE html>
<html>
<body onload="test();">
<script>
var number=1;
var input='<div><input type="text" <? if('+number+'==1){ ?> size="1" <? } else{ ?> size="100" <? } ?>><div>'+
'<div>'+number+'</div>'+
'<input type="text" <? if(1==1){ ?> size="1" <? } else{ ?> size="100" <? } ?>>';
function test(){
var div = document.getElementById('result');
div.innerHTML = div.innerHTML + input;
}
</script>
<div id="result"></div>
</body>
</html>
Can someone help me with code above? For some reason my first input box has size of 100 even should be 1.
It is because php code is executed before js code. While php is executed it tries to check '+number+' is 1 which it is not. It is a string.
Php code is executed in server and js code in browser. That is huge difference.
You can't access JavaScript variables like number
in php
.
If you want to use number
you need to do it in JavaScript
like this:
<!DOCTYPE html>
<html>
<body onload="test();">
<script>
var number = 1;
var input = '<div><input type="text";';
input += number == 1 ? ' size="1" ' : ' size="100" ';
input += '><div>';
input += '<div>' + number + '</div>';
input += '<input type="text" ';
input += 1 == 1 ? ' size="1" ' : ' size="100" ';
input += '>';
function test() {
var div = document.getElementById('result');
div.innerHTML = div.innerHTML + input;
}
</script>
<div id="result"></div>
</body>
</html>