javascript复选框默认返回第一个值而不是选定的值

问题描述 投票:0回答:1

PHP

// iterating through the data and displaying in table format

foreach($data['schoolList'] as $school)
    {
    echo'<tr>';
    echo '<td><input type=checkbox class=check id=check value='.$school['sid'].'></td>';
    echo '<td>'.$school['sid'] .'</td>';
    echo '<td>'.$school['name'] .'</td>';
    echo '<td>'.$school['specialization'].'</td>';
    echo'</tr>';
} 
echo '<button onclick="myFunction()">Apply</button>';

JavaScript的

<script>
    //to restrict the user to select only 3 checkboxes

    $("input:checkbox").click(function() {
        let x = $("input:checkbox:checked").length >= 3;     
        $("input:checkbox").not(":checked").attr("disabled",x);
    });
    let y=[];               
    function myFunction() {
        y= document.getElementById("check").value;
        console.log(y);  
    }                             
</script>

即使我选择了多个复选框,IT也只记录第一个学校ID,无论我选择什么!任何人都可以帮我如何记录所有控制台值!谢谢!

javascript php jquery
1个回答
1
投票

document.getElementById("check")仅使用id="check"返回第一个元素,因为ID是唯一标识符。

使用getElementsByClassName()代替或使用jQuery:

<script>
    //to restrict the user to select only 3 checkboxes

    $("input:checkbox").click(function() {
        let x = $("input:checkbox:checked").length >= 3;     
        $("input:checkbox").not(":checked").prop("disabled", x);
    });
    let y = [];               
    function myFunction() {
        $(":checked").each(function () {
            y.push($(this).val());
        });
        console.log(y);  
    }                             
</script>
© www.soinside.com 2019 - 2024. All rights reserved.