猿问

如何从ajax中的输入中获取数组中的检查值

im试图从我的ajax中获取我检查的输入值,但它只返回我的第一个勾选...这是我的代码


function getBranchAjax(cuid, stid) {

    $.ajaxSetup({

        headers: {

            'X-CSRF-Token': $('meta[name=csrf-token]').attr('content')

        }

    });

    $.ajax({

        url: "{{ route('reporting.getBranchAjax',['cuid','stid']) }}",

        method: 'GET',

        data: { cuid: cuid, stid: stid },

        dataType: 'json',

        success: function (data) {


            console.log(data);

            console.log(data.branch.length);



            //remove all option except the first option the append with new option

            //remove all option except the first option the append with new option

            for (var x = 0; x < data.branch.length; x++) {

                //console.log(data.branch[x].cb_branch_Name);

                $('#brRecord').append(`<tr><td style='width: 110px; text-align: left;'>${data.branch[x].cb_branchcode}

    </td><td style='width: 600px; text-align: left;'>${data.branch[x].cb_branch_Name}</td>

     <td style='width: 20px;'> 

    <input type="checkbox" class="ss" name="ss" id="ss" value="${data.branch[x].cb_branch_Name}" /></td><td>


                                    </td></tr>`);


            }



        },

        fail: function (xhr, textStatus, errorThrown) {

            alert('request failed');

        }

    })

}

按类名获取值,这只是我第一次逐笔报价的返回值


var checkedValue = null; 

var inputElements = document.getElementsByClassName('ss');

for(var i=0; inputElements[i]; ++i){

    if(inputElements[i].checked){

        checkedValue = inputElements[i].value;

        break;

    }

}


console.log(checkedValue); // only return a value of my first tick

我希望根据我的输入价格变动值获得更多价值


喵喵时光机
浏览 76回答 2
2回答

慕神8447489

多个值需要保存在数组(或类似数组)中。例如:var checkedValues = Array.from(document.getElementsByClassName('ss')).filter(el => el.checked).map(el => el.value);console.log(checkedValues);或者,由于问题被标记为 jQuery:var checkedValues = jQuery('.ss:checked').get().map(el => el.value);console.log(checkedValues);使用数组中的值,您可以对它们执行任何操作,例如显示它们或对它们执行一些转换。

精慕HU

这是因为您在 for 循环中添加了一个中断。删除它将解决您的问题。for(var i=0; inputElements[i]; ++i){&nbsp; &nbsp; &nbsp; &nbsp; if(inputElements[i].checked){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; checkedValue = inputElements[i].value;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }如果要获取所有最新单击的复选框,可以使用 onChangefunction checkedInput()&nbsp;{&nbsp;cosnt checkedValue = [];&nbsp;for(var i=0; inputElements[i]; ++i){&nbsp; &nbsp; &nbsp; &nbsp; if(inputElements[i].checked){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; checkedValue.push(inputElements[i].value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; return checkedValue ;}$(document).on('change', '#ss', function () {&nbsp;console.log(checkedInput());})
随时随地看视频慕课网APP
我要回答