programing

jquery를 사용하여 특정 클래스 이름을 가진 모든 확인란 가져오기

iphone6s 2023. 7. 26. 21:40
반응형

jquery를 사용하여 특정 클래스 이름을 가진 모든 확인란 가져오기

다음을 사용하여 페이지의 모든 확인란을 표시할 수 있습니다.

$('input[type=checkbox]').each(function () {
    var sThisVal = (this.checked ? $(this).val() : "");
});

그러나 지금은 포함하지 않으려는 다른 확인란이 있는 페이지에서 사용하고 있습니다.특정 클래스가 있는 선택된 확인란만 보도록 위의 코드를 변경하려면 어떻게 해야 합니까?

$('.theClass:checkbox:checked')클래스와 함께 선택된 모든 확인란을 제공합니다.theClass.

$('input:checkbox.class').each(function () {
       var sThisVal = (this.checked ? $(this).val() : "");
  });

를 들어 설명합니다.

:checkbox확인란의 선택기입니다(사실, 당신은 생략할 수 있습니다).input초기 버전의 라이브러리에서 이 작업을 수행하면 이상한 결과를 얻을 수 있는 틈새 사례를 찾았지만 선택기의 일부입니다.저는 그들이 이후 버전에서 고정되어 있다고 확신합니다..class다음을 포함하는 요소 클래스 속성의 선택기입니다.class.

의무적인 예:

var checkedVals = $('.theClass:checkbox:checked').map(function() {
    return this.value;
}).get();
alert(checkedVals.join(","));
$('input.yourClass:checkbox:checked').each(function () {
    var sThisVal = $(this).val();
});

클래스 이름 "yourClass"의 모든 확인란이 표시됩니다.이 예제는 조건부 검사 대신 jQuery selector check를 사용하기 때문에 마음에 듭니다.개인적으로 배열을 사용하여 값을 저장한 다음 필요에 따라 다음과 같이 사용할 수 있습니다.

var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
    arr.push($(this).val());
});

선택한 모든 확인란의 을 배열로 가져와야 하는 경우:

let myArray = (function() {
    let a = [];
    $(".checkboxes:checked").each(function() {
        a.push(this.value);
    });
    return a;
})()
 $('input.theclass[type=checkbox]').each(function () {
   var sThisVal = (this.checked ? $(this).val() : "");
 });

특정한 경우에 도움이 되는지 잘 모르겠습니다. 또한 사용자의 경우에만 포함하려는 확인란이 단일 양식 또는 디바 테이블의 일부인지는 잘 모르겠습니다. 그러나 특정 요소 내의 모든 확인란을 항상 선택할 수 있습니다.예:

<ul id="selective">
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
</ul>

그런 다음 다음 jQuery를 사용하면 ID="dump"인 UL 내의 확인란만 통과합니다.

$('#selective input:checkbox').each(function () {
 var sThisVal = (this.checked ? $(this).val() : "");
});

다음과 같은 것을 사용할 수 있습니다.
HTML:

<div><input class="yourClass" type="checkbox" value="1" checked></div>
<div><input class="yourClass" type="checkbox" value="2"></div>
<div><input class="yourClass" type="checkbox" value="3" checked></div>
<div><input class="yourClass" type="checkbox" value="4"></div>


JQuery:

$(".yourClass:checkbox").filter(":checked")


1과 3의 값을 선택합니다.

모든 값을 배열로 가져오는 간단한 방법

var valores = (function () {
    var valor = [];
    $('input.className[type=checkbox]').each(function () {
        if (this.checked)
            valor.push($(this).val());
    });
    return valor;

})();

console.log(valores);
 $('input.myclass[type=checkbox]').each(function () {
   var sThisVal = (this.checked ? $(this).val() : ""); });

jQuery 클래스 선택기를 참조하십시오.

이렇게 해보세요.

let values = (function() {
                let a = [];
                $(".chkboxes:checked").each(function() {
                    a.push($(this).val());
                });
                return a;
            })();
<input type="checkbox" id="Checkbox1" class = "chk" value = "1" />
<input type="checkbox" id="Checkbox2" class = "chk" value = "2" />
<input type="checkbox" id="Checkbox3" class = "chk" value = "3" />
<input type="checkbox" id="Checkbox4" class = "chk" value = "4" />
<input type="button" id="demo" value = "Demo" />

<script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
    $("#demo").live("click", function () {
        $("input:checkbox[class=chk]:checked").each(function () {
            alert("Id: " + $(this).attr("id") + " Value: " + $(this).val());
        });
    });
</script>

http://www.jqueryfaqs.com/Articles/Get-values-of-all-checked-checkboxes-by-class-name-using-jQuery.aspx

저는 이것이 이미 이 질문에 대한 많은 훌륭한 답을 가지고 있다는 것을 알고 있지만, 저는 이것을 둘러보다가 발견했고 사용하기가 정말 쉽다는 것을 알게 되었습니다.다른 사람들을 위해 나눠줄 줄 알았는데요

HTML:

<fieldset>
    <!-- these will be affected by check all -->
    <div><input type="checkbox" class="checkall"> Check all</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>
<fieldset>
    <!-- these won't be affected by check all; different field set -->
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>

jQuery:

$(function () {
    $('.checkall').on('click', function () {
        $(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
    });
});

참조: jQuery로 가장 쉬운 "모두 확인"

클래스 이름별로 선택한 확인란의 ID를 가져오는 간단한 방법:

$(".yourClassName:checkbox:checked").each(function() {
     console.log($(this).attr("id"));
});

HTML

 <p> <input type="checkbox" name="fruits" id="fruits"  value="1" /> Apple </p>
 <p> <input type="checkbox" name="fruits" id="fruits"  value="2" /> Banana </p>
 <p> <input type="checkbox" name="fruits" id="fruits"  value="3" /> Mango </p>
 <p> <input type="checkbox" name="fruits" id="fruits"  value="4" /> Grape </p>

제이쿼리

선택한 과일 값을 저장하기 위해 배열을 정의합니다.

 fruitArray = [];

$.각각 선택한 확인란을 반복하고 배열로 밀어넣습니다.

 $.each($("input[name='fruits']:checked"), function (K, V) {    
    fruitArray.push(V.value);        
});

                                       
$(document).ready(function(){
    $('input.checkD[type="checkbox"]').click(function(){
        if($(this).prop("checked") == true){
            $(this).val('true');
        }
        else if($(this).prop("checked") == false){
            $(this).val('false');
        }
    });
});
$("input:checked.yourClassName").each(function(){
   console.log($(this).val());
});

그것도 일입니다.

확인란에만 지정된 클래스 이름이 있는 경우 다음을 지정할 필요가 없습니다.:checkbox필터를 씌우기

const newArray = $('.yourClass:checked').map(function(){return $(this).val()}).get();
console.log(newArray);
$("input[name='<your_name_of_selected_group_checkboxes>']:checked").val()

언급URL : https://stackoverflow.com/questions/5450104/using-jquery-to-get-all-checked-checkboxes-with-a-certain-class-name

반응형