Get checkbox values using checkbox name using jquery

前端 未结 8 1826
刺人心
刺人心 2021-02-05 00:32

I have several input checkboxes, (they name is same for send array on server).

So, I need get each value this checkboxes and I want use as selector checkbox names, this

相关标签:
8条回答
  • 2021-02-05 00:33

    You should include the brackets as well . . .

    <input type="checkbox" name="bla[]" value="1" />
    

    therefore referencing it should be as be name='bla[]'

    $(document).ready( function () { 
    
       $("input[name='bla[]']").each( function () {
           alert( $(this).val() );
       });
    
    });
    
    0 讨论(0)
  • 2021-02-05 00:41

    I would like to add that if you're trying to get all of the check-boxes with that name that have been selected, you would want to use the following syntax:

    $("[name='bla[]']:checked").each(function () {
        // do stuff
    });
    

    Make sure there is not a space between the closing ] and :checked

    0 讨论(0)
  • 2021-02-05 00:44
    $('[name="CheckboxName"]:checked').each(function () {
        // do stuff
    });
    
    0 讨论(0)
  • 2021-02-05 00:44

    // get checkbox values using checkbox's name

    <head>
            <script>
            function getCheckBoxValues(){
                $('[name="checkname"]').each( function (){
                    alert($(this).val());
                });
            }
            </script>
        </head>
        <body>
            <input type="checkbox" name="checkname" value='1'/>
            <input type="checkbox" name="checkname" value='2'/>
            <input type="checkbox" name="checkname" value='3'/>
            <input type="button" value="CheckBoxValues" onclick="getCheckBoxValues()"/>
        </body>
    

    // get only the values witch are checked

    function getCheckBoxValues(){
            $('[name="checkname"]').each( function (){
                if($(this).prop('checked') == true){
                    alert($(this).val());
                }
            });
        }
    
    0 讨论(0)
  • 2021-02-05 00:51

    If you like to get a list of all values of checked checkboxes (e.g. to send them as a list in one AJAX call to the server), you could get that list with:

    var list = $("input[name='bla[]']:checked").map(function () {
        return this.value;
    }).get();
    
    0 讨论(0)
  • 2021-02-05 00:51
    $("input[name='bla[]']").each( function () {
        alert($(this).val());
    });
    
    0 讨论(0)
提交回复
热议问题