How to retrieve checkboxes values in jQuery

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

    The following may be useful since I got here looking for a slightly different solution. My script needed to automatically loop through input elements and had to return their values (for jQuery.post() function), the problem was with checkboxes returning their values regardless of checked status. This was my solution:

    jQuery.fn.input_val = function(){
    
        if(jQuery(this).is("input[type=checkbox]")) {
            if(jQuery(this).is(":checked")) {
                return jQuery(this).val();
            } else {
                return false;
            }
        } else {
            return jQuery(this).val();
        }
    };
    

    Usage:

    jQuery(".element").input_val();
    

    If the given input field is a checkbox, the input_val function only returns a value if its checked. For all other elements, the value is returned regardless of checked status.

提交回复
热议问题