How to retrieve checkboxes values in jQuery

前端 未结 15 2024
时光说笑
时光说笑 2020-11-22 10:11

How to use jQuery to get the checked checkboxes values, and put it into a textarea immediately?

Just like this code:


  
  &l         


        
相关标签:
15条回答
  • 2020-11-22 11:08

    Here's one that works (see the example):

     function updateTextArea() {         
         var allVals = [];
         $('#c_b :checked').each(function() {
           allVals.push($(this).val());
         });
         $('#t').val(allVals);
      }
     $(function() {
       $('#c_b input').click(updateTextArea);
       updateTextArea();
     });
    

    Update

    Some number of months later another question was asked in regards to how to keep the above working if the ID changes. Well, the solution boils down to mapping the updateTextArea function into something generic that uses CSS classes, and to use the live function to monitor the DOM for those changes.

    0 讨论(0)
  • 2020-11-22 11:09
       $(document).ready(function() {
            $(':checkbox').click(function(){
               var cObj = $(this);
               var cVal = cObj.val();
               var tObj = $('#t');
               var tVal = tObj.val();
               if( cObj.attr("checked")) {
                  tVal = tVal + "," + cVal; 
                  $('#t').attr("value", tVal);
               } else {
                  //TODO remove unchecked value.
               }
            });
        });
    
    0 讨论(0)
  • 2020-11-22 11:10

    I have had a similar problem and this is how i solved it using the examples above:

     $(".ms-drop").click(function () {
            $(function showSelectedValues() {
                alert($(".ms-drop input[type=checkbox]:checked").map(
                   function () { return this.value; }).get().join(","));
            });
        });
    
    0 讨论(0)
提交回复
热议问题