Get value if checkbox checked

后端 未结 6 1366
情歌与酒
情歌与酒 2021-01-23 14:21

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?

相关标签:
6条回答
  • 2021-01-23 15:07

    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();   
    
    0 讨论(0)
  • 2021-01-23 15:10

    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('');
           }
        });
        )
    
    0 讨论(0)
  • 2021-01-23 15:11

    Since you're asking how to hide it:

    $('.active-usb').toggle(this.checked);
    
    0 讨论(0)
  • 2021-01-23 15:17

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

    0 讨论(0)
  • 2021-01-23 15:17

    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();
    
    0 讨论(0)
  • 2021-01-23 15:20

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

    0 讨论(0)
提交回复
热议问题