I was trying to change the value of a variable according to the status of a checkbox:
<script type="text/javascript">
if(document.getElementByType('checkbox').checked)
{
var a="checked";
}
else
{
var a="not checked";
}
document.getElementById('result').innerHTML ='result '+a;
</script>
<input type="checkbox" value="1"/>Checkbox<br/>
<br/>
<span id="result"></span>
What's the problem with this code?
Try this:
if (document.querySelector('input[type=checkbox]').checked) {
Code suggestion:
<input type="checkbox" />Checkbox<br/>
<span id="result"></span>
<script type="text/javascript">
window.onload = function () {
var input = document.querySelector('input[type=checkbox]');
function check() {
var a = input.checked ? "checked" : "not checked";
document.getElementById('result').innerHTML = 'result ' + a;
}
input.onchange = check;
check();
}
</script>
In your post you have the javascript before the HTML, in this case the HTML should be first so the javascript can "find it". OR use, like in my example a window.onload
function, to run the code after the page loaded.