dimanche 17 janvier 2021

Why is the checked checkbox null?

Below it's a very simple javascript function. When I click the button it's supposed to show me the value of the checked checkbox but it't prints out an error in the console saying the checkedValue is null?

I tried looping through the checkboxes and getting the checked one and i get the same error. I would really appreciate some help!

<body>
<p id='txt'>here: </p>
<button id="btn" type="button" onclick="ok" >Click </button>

<input type="checkbox" class="ckb" value="1">one
<input type="checkbox" class="ckb" value="2">two 
<input type="checkbox" class="ckb" value="3">three
<script>
var checkedValue = document.querySelectorAll('.ckb').checked;

document.getElementById('btn').addEventListener('click', function(){
document.getElementById('txt').innerText = checkedValue.value ;
});
</script>
</body>

Looping through the checkboxes

 var checkedValue; 
 var inputElements = document.querySelectorAll('.ckb');
 for(var i=0; i < inputElements.length; i++){
    if(inputElements[i].checked===true){
         checkedValue = inputElements[i];
         break;
    }
}



Aucun commentaire:

Enregistrer un commentaire