Programing

jQuery는 체크 박스의 값을 배열로 가져옵니다.

crosscheck 2020. 7. 12. 09:52
반응형

jQuery는 체크 박스의 값을 배열로 가져옵니다.


현재 선택된 모든 확인란의 값을 가져 와서 배열에 저장하려고합니다. 지금까지 내 코드는 다음과 같습니다.

 $("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
      return $(this).val();
    });
    console.log(searchIDs);
  });

그러나 이것은 내가 필요 이상으로 출력합니다. 나는 가치를 얻을뿐만 아니라 원하지 않는 다른 것들을 얻습니다.

[ "51729b62c9f2673e4c000004", "517299e7c9f26782a7000003", "51729975c9f267f3b5000002", prevObject : jQuery.fn.jQuery.init [3], 컨텍스트 : 문서, jquery : "1.9.1", 생성자 : 함수, 초기화 : 기능…]

ID 만 원합니다 (이 경우 처음 3 개 항목).

$.each값을 배열에 사용 하고 밀어서 원하는 출력을 얻습니다.

$("#find-table input:checkbox:checked").each(function(){ myArray.push($(this).val()); })

[ "51729b62c9f2673e4c000004", "517299e7c9f26782a7000003", "51729975c9f267f3b5000002"]

그러나 $.map코드 줄을 절약하고 더 예쁘기 때문에을 사용하고 싶습니다 .

감사


.get()결과 jQuery 객체를 실제 배열로 바꾸려면 맨 끝을 호출 하십시오.

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
      return $(this).val();
    }).get(); // <----
    console.log(searchIDs);
});

문서 :

반환 값은 배열을 포함하는 jQuery 객체이므로 기본 배열로 작업하기 위해 결과에서 .get ()을 호출하는 것이 매우 일반적입니다.


데모 : http://jsfiddle.net/PBhHK/

$(document).ready(function(){

    var searchIDs = $('input:checked').map(function(){

      return $(this).val();

    });
    console.log(searchIDs.get());

});

get ()을 호출하면 사양에 기록 된 배열이 있습니다 : http://api.jquery.com/map/

$(':checkbox').map(function() {
      return this.id;
    }).get().join();

함수 .toArray()의 끝에 추가 해야 .map()합니다

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
        return $(this).val();
    }).toArray();
    console.log(searchIDs);
});

데모 : http://jsfiddle.net/sZQtL/


I refactored your code a bit and believe I came with the solution for which you were looking. Basically instead of setting searchIDs to be the result of the .map() I just pushed the values into an array.

$("#merge_button").click(function(event){
  event.preventDefault();

  var searchIDs = [];

  $("#find-table input:checkbox:checked").map(function(){
    searchIDs.push($(this).val());
  });

  console.log(searchIDs);
});

I created a fiddle with the code running.


     var ids = [];

$('input[id="find-table"]:checked').each(function() {
   ids.push(this.value); 
});

This one worked for me!


Needed the form elements named in the HTML as an array to be an array in the javascript object, as if the form was actually submitted.

If there is a form with multiple checkboxes such as:

<input name='breath[0]' type='checkbox' value='presence0'/>
<input name='breath[1]' type='checkbox' value='presence1'/>
<input name='breath[2]' type='checkbox' value='presence2'/>
<input name='serenity'  type='text' value='Is within the breath.'/>
...

The result is an object with:

data = {
   'breath':['presence0','presence1','presence2'],
   'serenity':'Is within the breath.'
}


var $form = $(this),
    data  = {};

$form.find("input").map(function()
{
    var $el  = $(this),
        name = $el.attr("name");

    if (/radio|checkbox/i.test($el.attr('type')) && !$el.prop('checked'))return;

    if(name.indexOf('[') > -1)
    {
        var name_ar = name.split(']').join('').split('['),
            name    = name_ar[0],
            index   = name_ar[1];

        data[name]  = data[name] || [];
        data[name][index] = $el.val();
    }
    else data[name] = $el.val();
});

And there are tons of answers here which helped improve my code, but they were either too complex or didn't do exactly want I wanted: Convert form data to JavaScript object with jQuery

Works but can be improved: only works on one-dimensional arrays and the resulting indexes may not be sequential. The length property of an array returns the next index number as the length of the array, not the actually length.

Hope this helped. Namaste!


var idsArr = [];

$('#tableID').find('input[type=checkbox]:checked').each(function() {
    idsArr .push(this.value);
});

console.log(idsArr);

Do not use "each". It is used for operations and changes in the same element. Use "map" to extract data from the element body and using it somewhere else.


here allows is class of checkboxes on pages and var allows collects them in an array and you can check for checked true in for loop then perform the desired operation individually. Here I have set custom validity. I think it will solve your problem.

  $(".allows").click(function(){
   var allows = document.getElementsByClassName('allows');
   var chkd   = 0;  
   for(var i=0;i<allows.length;i++)
   {
       if(allows[i].checked===true)
       {
           chkd = 1;
       }else
       {

       }
   }

   if(chkd===0)
   {
       $(".allows").prop("required",true);
       for(var i=0;i<allows.length;i++)
        {
        allows[i].setCustomValidity("Please select atleast one option");
        }

   }else
   {
       $(".allows").prop("required",false);
       for(var i=0;i<allows.length;i++)
        {
        allows[i].setCustomValidity("");
        }
   }

}); 

참고URL : https://stackoverflow.com/questions/16170828/jquery-get-values-of-checked-checkboxes-into-array

반응형