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?
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?
Share Improve this question edited Sep 25, 2024 at 14:53 user17726418 2,3658 gold badges16 silver badges34 bronze badges asked Oct 16, 2013 at 12:37 user2533777user25337776 Answers
Reset to default 7Try this:
if (document.querySelector('input[type=checkbox]').checked) {
Demo here
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.
$('#myForm').on('change', 'input[type=checkbox]', function() {
this.checked ? this.value = 'apple' : this.value = 'pineapple';
});
try something like this
<script type="text/javascript">
function update_value(chk_bx){
if(chk_bx.checked)
{
var a="checked";}
else{
var a="not checked";
}
document.getElementById('result').innerHTML ='result '+a;
}
</script>
<input type="checkbox" value="1" onchange="update_value(this);"/>Checkbox<br/>
<span id="result"></span>
Too complicated. Inline code makes it cool.
<input type="checkbox" onclick="yourBooleanVariable=!yourBooleanVariable;">
For those who tried the previous options and still have a problem for any reason, you may go this way using the .prop() jquery function:
$(document.body).on('change','input[type=checkbox]',function(){
if ($(this).prop('checked') == 1){
alert('checked');
}else{
alert('unchecked');
}
This code will run only once and check initial checkbox state. You have to add event listener for onchange
event.
window.onload = function() {
document.getElementByType('checkbox').onchange = function() {
if(document.getElementByType('checkbox').checked) {
var a="checked";
} else {
var a="not checked";
}
document.getElementById('result').innerHTML ='result '+a;
}
}