我有这些复选框:

<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />

等等。它们中大约有6个是手工编码的(即不是从db中获取的),所以它们可能会在一段时间内保持相同。

我的问题是我如何能得到他们都在一个数组(javascript),所以我可以使用他们,而使AJAX $。使用Jquery发布请求。

任何想法吗?

编辑:我只希望将选定的复选框添加到数组中


格式:

$("input:checkbox[name=type]:checked").each(function(){
    yourArray.push($(this).val());
});

希望它能起作用。


这应该可以达到目的:

$('input:checked');

我不认为你有其他可以检查的元素,但如果你有,你必须让它更具体:

$('input:checkbox:checked');

$('input:checkbox').filter(':checked');

我没有测试它,但它应该工作

<script type="text/javascript">
var selected = new Array();

$(document).ready(function() {

  $("input:checkbox[name=type]:checked").each(function() {
       selected.push($(this).val());
  });

});

</script>

在MooTools 1.3(撰写本文时的最新版本)中:

var array = [];
$$("input[type=checkbox]:checked").each(function(i){
    array.push( i.value );
});

var chk_arr =  document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;             

for(k=0;k< chklength;k++)
{
    chk_arr[k].checked = false;
} 

在Javascript中,它是这样的(演示链接):

// get selected checkboxes
function getSelectedChbox(frm) {
  var selchbox = [];// array that will store the value of selected checkboxes
  // gets all the input tags in frm, and their number
  var inpfields = frm.getElementsByTagName('input');
  var nr_inpfields = inpfields.length;
  // traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
  for(var i=0; i<nr_inpfields; i++) {
    if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
  }
  return selchbox;
}   

使用Jquery

你只需要添加类到每个输入,我有添加类“源”,你当然可以改变它

<input class="source" type="checkbox" name="type" value="4" />
<input class="source" type="checkbox" name="type" value="3" />
<input class="source" type="checkbox" name="type" value="1" />
<input class="source" type="checkbox" name="type" value="5" />

<script type="text/javascript">
$(document).ready(function() {
    var selected_value = []; // initialize empty array 
    $(".source:checked").each(function(){
        selected_value.push($(this).val());
    });
    console.log(selected_value); //Press F12 to see all selected values
});
</script>

如果你想使用一个普通的JS,你可以像@zahid-ullah那样做,但要避免循环:

  var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
    return c.checked;
  }).map(function(c) {
    return c.value;
  });

ES6中的相同代码看起来更好:

var values = [].filter.call(document.getElementsByName('fruits[]'), (c) => c.checked).map(c => c.value);

window.serialize = function serialize() { var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) { return c.checked; }).map(function(c) { return c.value; }); document.getElementById('serialized').innerText = JSON.stringify(values); } label { display: block; } <label> <input type="checkbox" name="fruits[]" value="banana">Banana </label> <label> <input type="checkbox" name="fruits[]" value="apple">Apple </label> <label> <input type="checkbox" name="fruits[]" value="peach">Peach </label> <label> <input type="checkbox" name="fruits[]" value="orange">Orange </label> <label> <input type="checkbox" name="fruits[]" value="strawberry">Strawberry </label> <button onclick="serialize()">Serialize </button> <div id="serialized"> </div>


var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
        return this.value;
    }).get();

用这个:

var arr = $('input:checkbox:checked').map(function () {
  return this.value;
}).get();

ES6版本:

const values = Array
  .from(document.querySelectorAll('input[type="checkbox"]'))
  .filter((checkbox) => checkbox.checked)
  .map((checkbox) => checkbox.value);

function getCheckedValues() { return Array.from(document.querySelectorAll('input[type="checkbox"]')) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); } const resultEl = document.getElementById('result'); document.getElementById('showResult').addEventListener('click', () => { resultEl.innerHTML = getCheckedValues(); }); <input type="checkbox" name="type" value="1" />1 <input type="checkbox" name="type" value="2" />2 <input type="checkbox" name="type" value="3" />3 <input type="checkbox" name="type" value="4" />4 <input type="checkbox" name="type" value="5" />5 <br><br> <button id="showResult">Show checked values</button> <br><br> <div id="result"></div>


纯JS

对于那些不想使用jQuery的人

var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')

for (var i = 0; i < checkboxes.length; i++) {
  array.push(checkboxes[i].value)
}

使用注释if块,以防止添加值已经在数组中,如果你使用按钮点击或其他东西来运行插入

$('#myDiv').change(function() { var values = []; { $('#myDiv :checked').each(function() { //if(values.indexOf($(this).val()) === -1){ values.push($(this).val()); // } }); console.log(values); } }); <div id="myDiv"> <input type="checkbox" name="type" value="4" /> <input type="checkbox" name="type" value="3" /> <input type="checkbox" name="type" value="1" /> <input type="checkbox" name="type" value="5" /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


在勾选时添加复选框的值,在勾选时减去该值

$('#myDiv').change(function() { var values = 0.00; { $('#myDiv :checked').each(function() { //if(values.indexOf($(this).val()) === -1){ values=values+parseFloat(($(this).val())); // } }); console.log( parseFloat(values)); } }); <div id="myDiv"> <input type="checkbox" name="type" value="4.00" /> <input type="checkbox" name="type" value="3.75" /> <input type="checkbox" name="type" value="1.25" /> <input type="checkbox" name="type" value="5.50" /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


你可以尝试这样做:

$('input[type="checkbox"]').change(function(){
       var checkedValue = $('input:checkbox:checked').map(function(){
                return this.value;
            }).get();         
            alert(checkedValue);   //display selected checkbox value     
 })

Here

$('input[type="checkbox"]').change(function() call when any checkbox checked or unchecked, after this
$('input:checkbox:checked').map(function()  looping on all checkbox,

这是我的代码,同样的问题,有人也可以尝试这个。 jquery

<script>
$(document).ready(function(){`
$(".check11").change(function(){
var favorite1 = [];        
$.each($("input[name='check1']:checked"), function(){                    
favorite1.push($(this).val());
document.getElementById("countch1").innerHTML=favorite1;
});
});
});
</script>

函数selectedValues(避署){ Var arr = []; For (var I = 0;I < ele.length;我+ +){ 如果(避署[我]。Type == 'checkbox' && ele[i].checked){ arr.push(避署[我]。value); } } 返回arr; }


在现代浏览器(不支持IE,遗憾的是在撰写本文时不支持iOS Safari)中使用香草JS的另一种方式是使用FormData.getAll():

var formdata   = new FormData(document.getElementById("myform"));
var allchecked = formdata.getAll("type"); // "type" is the input name in the question

// allchecked is ["1","3","4","5"]  -- if indeed all are checked

纯JavaScript,不需要临时变量:

Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);

var array = []
    $("input:checkbox[name=type]:checked").each(function(){
        array.push($(this).val());
    });

按输入名称选择复选框

var category_id = [];

$.each($("input[name='yourClass[]']:checked"), function(){                    
    category_id.push($(this).val());
});

可以使用我创建的这个函数吗

function getCheckBoxArrayValue(nameInput){
    let valores = [];
    let checked = document.querySelectorAll('input[name="'+nameInput+'"]:checked');
    checked.forEach(input => {
        let valor = input?.defaultValue || input?.value;
        valores.push(valor);
    });
    return(valores);
}

要使用它,就这样称呼它

getCheckBoxArrayValue("type");

 var idsComenzi = [];

    $('input:checked').each(function(){
        idsComenzi.push($(this).val());
    });

Array.from($(".yourclassname:checked"), a => a.value);

只是说说我的意见,说不定能帮到别人

const data = $checkboxes.filter(':checked').toArray().map((item) => item.value);

我已经有一个jQuery对象,所以我不会选择所有的复选框另一次,这就是为什么我使用jQuery的过滤器方法。然后我把它转换成一个JS数组,我映射数组返回项目的值。


使用下面的代码获取所有检查值

        var yourArray=[];
        $("input[name='ordercheckbox']:checked").each(function(){
            yourArray.push($(this).val());
        });
        console.log(yourArray);

这是一个老问题,但在2022年有一个更好的方法来实现它使用香草JS

我们不需要react或者花哨的框架。

我们只需要处理两个这样的onchange事件:

const types = [{id:1, name:'1'}, {id:2, name:'2'}, {id:3, name:'3'}, {id:4, name:'4'}, {id:5, name:'5'}, {id:6, name:'6'}] const all = document.getElementById('select-all') const summary = document.querySelector('p') let selected = new Set() const onCheck = event => { event.target.checked ? selected.add(event.target.value) : selected.delete(event.target.value) summary.textContent = `[${[...selected].join(', ')} | size: ${selected.size}] types selected.` all.checked = selected.size === types.length } const createCBInput = t => { const ol = document.querySelector('ol') const li = document.createElement('li') const input = document.createElement('input') input.type = 'checkbox' input.id = t.id input.name = 'type' input.value = t.id input.checked = selected.has(t.id) input.onchange = onCheck const label = document.createElement('label') label.htmlFor = t.id label.textContent = t.name li.append(input, label) ol.appendChild(li) } const onSelectAll = event => { const checked = event.target.checked for (const t of types) { const cb = document.getElementById(t.id) cb.checked = checked ? true : selected.has(t.id) const event = new Event('change') cb.dispatchEvent(event) } } all.checked = selected.size === types.length all.onchange = onSelectAll for (const t of types) { createCBInput(t) } ol { list-style-type: none; padding-left: 0; } <ol> <li> <input type="checkbox" id="select-all"> <label for="select-all"><strong>Select all</strong></label> </li> </ol> <p></p>


$(document).ready(function() { $('input[type="checkbox"]').click(function() { var arr =[]; $('input[type="checkbox"]:checked').each(function() { //arr.push($(this).parent('p').text()+'\n'); arr.push($(this).val()+'\n'); }); var array = arr.toString().split(',') $("#text").val(array.join("")); }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>Append value when checkbox is checked</p> <textarea rows="4" id="text" style="width: 100%"> </textarea> <div id="checkboxes"> <p><input type="checkbox" value="Item 1"><span>&nbsp;&nbsp; Item 1</span></p> <p><input type="checkbox" value="Item 2"><span>&nbsp;&nbsp; Item 2</span></p> <p><input type="checkbox" value="Item 3"><span>&nbsp;&nbsp; Item 3</span></p> <p><input type="checkbox" value="Item 4"><span>&nbsp;&nbsp; Item 4</span></p> <p><input type="checkbox" value="Item 5"><span>&nbsp;&nbsp; Item 5</span></p> </div>


 var checked= $('input[name="nameOfCheckbox"]:checked').map(function() {
   return this.value;
}).get();