How to retrieve checkboxes values in jQuery

前端 未结 15 2278
时光说笑
时光说笑 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:53

    Your question is quite vague but I think this is what you need:

    $(function() { 
        $('input[type="checkbox"]').bind('click',function() {
            if($(this).is(':checked')) {
                $('#some_textarea').html($(this).val());
             }
       });
    });
    

    Edit: Oh, okay.. there you go... You didn't have the HTML up before. Anyways, yeah, I thought you meant to put the value in a textarea when it gets clicked. If you want the checked checkboxes' values to be put into the textarea (maybe with a nice comma-seperation) on page load it would be as simple as:

    $(function() { 
        $('#c_b input[type="checkbox"]:checked').each(function() { 
            $('#t').append(', '+$(this).val());
        });
    });
    

    Edit 2 As people have done, you can also do this to shortcut the lengthy selector I wrote:

    $('#c_b :checkbox:checked').each(function() {
        $('#t').append(', '+$(this).val());
    });
    

    ... I totally forgot about that shortcut. ;)

提交回复
热议问题