1

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();   

6 Answers 6

3

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">

Sign up to request clarification or add additional context in comments.

Comments

2

Since you're asking how to hide it:

$('.active-usb').toggle(this.checked);

Comments

2

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">

Comments

0

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();

Comments

0

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();   

Comments

0

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('');
       }
    });
    )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.