简体   繁体   中英

How to make a checkbox show/hide text with onChange event

I am working on a checkbox that shows a new textbox when clicked. It's just two textboxes where one of them is hidden. When the checkbox is checked it shows the hidden textbox and hides the already enabled textbox.

I am using the onChange event to show/hide, but I can only manage to turn it on once. And since I'm just starting out using Javascript, I haven't really worked out all the variables on how make two onChange events for the same checkbox (*. I am using onChange as it reacts to the checkbox itself, while onClick somehow only react to everything except the checkbox.

Another problem is that I'm using Wix Corvid to program it, and I don't get any functioning name or ID on the checkbox.

$w.onReady(function (){ 
$w('#checkboxGroup1').onChange((event)=> {
$w('#text108').show();
$w('#text106').hide();  
})
});

https://jsfiddle.net/x0gon2a9/4/

<input type="checkbox" class="checkbox" id="checkbox" value="chckbox1" checked="true"> checkbox1 <input type="text" id="input-1" value="input-1"> <input type="text" id="input-2" value="input-2" >

 if ($("#checkbox").is(":checked")) {
 $("#input-1").hide();
}else {
$("#input-1").show();
}
});

$("#checkbox").click(function(){
if ($("#checkbox").is(":checked")) { 
$("#input-1").hide();
$("#input-2").show();
}else {
$("#input-1").show();
$("#input-2").hide();
}
})

You need to check if it's checked or not first:

$w.onReady(function (){ 
$w('#checkboxGroup1').change((event)=> {
if($w('#checkboxGroup1').prop('checked') == true)
   $w('#text108').show();
else
   $w('#text106').hide();  
})
});

You can use class selector to add EventListener on the checkboxs and show hide the input based on that.

Here is the sample working code in vanilla javascript.

 const checkboxes = document.querySelectorAll('.checkbox'); checkboxes.forEach(checkbox => { checkbox.addEventListener('change', function() { const id = this.dataset.inputId; if (this.checked === true) { document.getElementById(id).style.display = 'block'; } else { document.getElementById(id).style.display = 'none'; } }); });
 <input type="checkbox" class="checkbox" data-input-id="input-1" value="chckbox1"> checkbox1 <input type="text" id="input-1" value="input-1" style="display: none"> <input type="checkbox" class="checkbox" data-input-id="input-2" value="chckbox1"> checkbox2 <input type="text" id="input-2" value="input-2" style="display: none">

Use event.target.checked

$w.onReady(function (){ 
  $w('#checkboxGroup1').onChange((event)=> {
    if (event.target.checked) {
       $w('#text108').show();
    } else {
      $w('#text106').hide();  
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM