How to retrieve checkboxes values in jQuery

前端 未结 15 2011
时光说笑
时光说笑 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 10:54
     function updateTextArea() {         
         var allVals = $('#c_b :checked').map(function() {
           return $(this).val();
         }).get();
         $('#t').val(allVals)
      }
     $(function() {
       $('#c_b input').click(updateTextArea);
       updateTextArea();
     });
    
    0 讨论(0)
  • 2020-11-22 10:56

    This works perfectly for me:

    alert($("input[name=chkboxName]:checked").map(function() {
        return this.value;
    }).get().join(","));
    

    Thanks Mohamed ElSheikh

    0 讨论(0)
  • 2020-11-22 11:01

    Anyway, you probably need something like this:

     var val = $('#c_b :checkbox').is(':checked').val();
     $('#t').val( val );
    

    This will get the value of the first checked checkbox on the page and insert that in the textarea with id='textarea'.

    Note that in your example code you should put the checkboxes in a form.

    0 讨论(0)
  • 2020-11-22 11:01

    A much easier and shorted way which I am using to accomplish the same, using answer from another post, is like this:

    var checkedCities = $('input[name=city]:checked').map(function() {
        return this.value;
    }).get();
    

    Originally the cities are retrieved from a MySQL database, and looped in PHP while loop:

    while ($data = mysql_fetch_assoc($all_cities)) {
    <input class="city" name="city" id="<?php echo $data['city_name']; ?>" type="checkbox" value="<?php echo $data['city_id']; ?>" /><?php echo $data['city_name']; ?><br />
    <?php } ?>
    

    Now, using the above jQuery code, I get all the city_id values, and submit back to the database using $.get(...)

    This has made my life so easy since now the code is fully dynamic. In order to add more cities, all I need to do is to add more cities in my database, and no worries on PHP or jQuery end.

    0 讨论(0)
  • 2020-11-22 11:04

    Try this one..

    var listCheck = [];
    console.log($("input[name='YourCheckBokName[]']"));
    $("input[name='YourCheckBokName[]']:checked").each(function() {
         console.log($(this).val());
         listCheck .push($(this).val());
    });
    console.log(listCheck);
    
    0 讨论(0)
  • 2020-11-22 11:07
    $("#t").text($("#cb").find(":checked").val())
    
    0 讨论(0)
提交回复
热议问题