Reputation: 3
i have this html code:
<input type="checkbox" id="template-contactform-baggages-custom" name="baggages" value="baggages" class="sm-form-control" onchange="showcheck(this, numbag)" />
<div id="numbag" class="hidden">
<input type="number" name="numofbag" value="" />
</div>
and this javascript function:
function showcheck(check, inputid) {
var checkid=check.id;
var checked=check.checked;
var inputelement = document.getElementById(inputid);
if(!checked){
inputelement.className = "";
inputelement.className = inputelement.className + "hidden";
}else{
inputelement.className = "";
inputelement.className = inputelement.className + "nothidden";
}
}
as you can see i want to hide or show my hidden div when i check my checkbox, i think that everything is ok with my function but console has a different idea..! Uncaught TypeError: Cannot set property 'className' of null, is the output
can anyone help me?
p.s. i made before a function with same logical and i have no problems
Upvotes: 0
Views: 1835
Reputation: 207501
onchange="showcheck(this, numbag)"
Should be
onchange="showcheck(this, 'numbag')"
And you need to add a space when you are setting the className. BUT the issue is your code will keep adding classes so it will have both hidden and not hidden. You should use classList
inputelement.classList.toggle('hidden', !checked);
inputelement.classList.toggle('nothidden', checked);
And since you are just setting classes (missed the part where you clear it), you can just do a ternary operator.
inputelement.className = checked? "nothidden" : "hidden";
Upvotes: 4