I\'m using a jQuery function to get the value of an checked checkbox.
How to hide the value in the span class \"active-usb\" if the checkbox is not checked anymore?
Use this Demo here
$("#getusb").on('change',function(){
if($('#getusb').prop('checked')== true){
$('.active-usb').text($("#getusb:checkbox:checked").val());
}else{
$('.active-usb').text('');
}
}).change();
Use the isChecked and on inside a document.ready
$(document).ready(
$("#getusb").on('change',function(){
if($(this).is(':checked')){
$('.active-usb').text($(this).val());
}
else{
$('.active-usb').text('');
}
});
)
Since you're asking how to hide it:
$('.active-usb').toggle(this.checked);
You can check ckeckbox status:
$("#getusb").on("change", function() {
//check if is checked
if (this.checked) {
//set the span text according to checkbox value
$('.active-usb').text(this.value);
} else {
//if is not checked hide span
$(".active-usb").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="active-usb"></span>
<br>
<input type="checkbox" id="getusb" value="Halterung für USB-Stick">
You can try something like this :-
$("#getusb").change(function(){
if($(this).is(':checked')){
$('.active-usb').text($(this).val());
}
else{
$('.active-usb').text('');
}
}).change();
OR
$("#getusb").change(function(){
$('.active-usb').text($(this).is(':checked') ? $(this).val() : '');
}).change();
You can use the checked
property to determine if the checkbox is checked or not. Then you can get the value of the checkbox that raised the event using this
. Try this:
$("#getusb").change(function(){
$('.active-usb').text(this.checked ? $(this).val() : '');
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="active-usb"></span><br>
<input type="checkbox" id="getusb" value="Halterung für USB-Stick">