Reputation: 23
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();
Upvotes: 1
Views: 1041
Reputation: 1235
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('');
}
});
)
Upvotes: 0
Reputation: 33228
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">
Upvotes: 2
Reputation: 337714
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">
Upvotes: 3
Reputation: 4637
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();
Upvotes: 0
Reputation: 35223
Since you're asking how to hide it:
$('.active-usb').toggle(this.checked);
Upvotes: 2
Reputation: 18883
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();
Upvotes: 0