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?
HTML
<span class="active-usb"></span><br>
<input type="checkbox" id="getusb" value="Halterung für USB-Stick">
Jquery
$("#getusb").change(function(){
$('.active-usb').text($("#getusb:checkbox:checked").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">
由于您正在询问如何隐藏它:
$('.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();
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('');
}
});
)
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.