Programing

jQuery로 확인란이 선택되어 있는지 확인하십시오.

lottogame 2020. 9. 27. 12:42
반응형

jQuery로 확인란이 선택되어 있는지 확인하십시오.


확인란 배열의 ID를 사용하여 확인란 배열의 확인란이 선택되었는지 어떻게 확인할 수 있습니까?

다음 코드를 사용하고 있지만 ID에 관계없이 항상 선택된 확인란 수를 반환합니다.

function isCheckedById(id) {
  alert(id);
  var checked = $("input[@id=" + id + "]:checked").length;
  alert(checked);

  if (checked == 0) {
    return false;
  } else {
    return true;
  }
}

ID는 문서에서 고유해야합니다. 즉, 이렇게하면 안됩니다 .

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

대신 ID를 삭제 한 다음 이름 또는 포함하는 요소별로 선택합니다.

<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

그리고 이제 jQuery :

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

$('#' + id).is(":checked")

확인란이 선택되어 있으면 가져옵니다.

이름이 같은 체크 박스 배열의 경우 다음과 같이 체크 박스 목록을 가져올 수 있습니다.

var $boxes = $('input[name=thename]:checked');

그런 다음 반복하여 확인한 내용을 확인하려면 다음을 수행하십시오.

$boxes.each(function(){
    // Do stuff here with this
});

확인 된 수를 찾으려면 다음을 수행하십시오.

$boxes.length;

$('#checkbox').is(':checked'); 

위의 코드는 확인란이 선택되어 있으면 true를 반환하고 그렇지 않으면 false를 반환합니다.


다음 방법은 모두 유용합니다.

$('#checkbox').is(":checked")

$('#checkbox').prop('checked')

$('#checkbox')[0].checked

$('#checkbox').get(0).checked

DOMelement 또는 인라인 "this.checked"는 피하는 것이 좋습니다. 대신 jQuery on 메소드는 이벤트 리스너를 사용해야합니다.


확인란이 선택되었는지 여부를 확인하는 jQuery 코드 :

if($('input[name="checkBoxName"]').is(':checked'))
{
  // checked
}else
{
 // unchecked
}

또는 :

if($('input[name="checkBoxName"]:checked'))
{
    // checked
}else{
  // unchecked
}

확인 된 속성에 대해 기억해야 할 가장 중요한 개념은 확인 된 속성과 일치하지 않는다는 것입니다. 속성은 실제로 defaultChecked 속성에 해당하며 확인란의 초기 값을 설정하는 데만 사용해야합니다. 확인 된 속성 값은 확인란의 상태에 따라 변경되지 않지만 확인 된 속성은 변경됩니다. 따라서 확인란이 선택되었는지 확인하는 브라우저 간 호환 방법은 속성을 사용하는 것입니다.

아래의 모든 방법이 가능합니다.

elem.checked 

$(elem).prop("checked") 

$(elem).is(":checked") 

이 코드를 사용할 수 있습니다.

if($("#checkboxId").is(':checked')){
     // Code in the case checkbox is checked.
} else {
     // Code in the case checkbox is NOT checked.
}

jQuery 문서에 따라 확인란의 선택 여부를 확인하는 방법은 다음과 같습니다. 예를 들어 확인란을 고려해 보겠습니다 ( 모든 예제에서 jsfiddle 작업 확인 ).

<input type="checkbox" name="mycheckbox" id="mycheckbox" />
<br><br>
<input type="button" id="test-with-checked" value="Test with checked" />
<input type="button" id="test-with-is" value="Test with is" />
<input type="button" id="test-with-prop" value="Test with prop" />

예 1-체크 됨

$("#test-with-checked").on("click", function(){
    if(mycheckbox.checked) {
        alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

예제 2-jQuery를 사용하면 NOTE-: checked

var check;
$("#test-with-is").on("click", function(){
    check = $("#mycheckbox").is(":checked");
    if(check) {
        alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

예제 3-jQuery prop 사용

var check;
$("#test-with-prop").on("click", function(){
    check = $("#mycheckbox").prop("checked");
    if(check) {
         alert("Checkbox is checked.");
    } else {
        alert("Checkbox is unchecked.");
    }
}); 

jsfiddle 작동 확인


이것을 시도 할 수 있습니다.

<script>
function checkAllCheckBox(value)
{
   if($('#select_all_').is(':checked')){
   $(".check_").attr ( "checked" ,"checked" );
    }
    else
    {
        $(".check_").removeAttr('checked');
    }

 }

</script>
<input type="checkbox" name="chkbox" id="select_all_" value="1" />


<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />

jquery에서 다음 권장 코드 중 하나를 사용할 수 있습니다.

if ( elem.checked ) {};
if ( $( elem ).prop( "checked" ) ) {};
if ( $( elem ).is( ":checked" ) ) {};

나는 OP가 jquery를 원한다는 것을 알고 있지만 내 경우에는 순수한 JS가 대답이므로 나와 같은 사람이 여기 있고 jquery가 없거나 사용하고 싶지 않은 경우 여기에 JS 답변이 있습니다.

document.getElementById("myCheck").checked

ID가 myCheck 인 입력을 체크하면 true를, 체크하지 않으면 false를 반환합니다.

그렇게 간단합니다.


간단하게 할 수 있습니다.

작업 바이올린

HTML

<input id="checkbox" type="checkbox" />

jQuery

$(document).ready(function () {
    var ckbox = $('#checkbox');

    $('input').on('click',function () {
        if (ckbox.is(':checked')) {
            alert('You have Checked it');
        } else {
            alert('You Un-Checked it');
        }
    });
});

또는 더 간단합니다.

$("#checkbox").attr("checked") ? alert("Checked") : alert("Unchecked");

If the checkbox is checked it will return true otherwise undefined


Simple Demo for checking and setting a check box.

jsfiddle!

$('.attr-value-name').click(function() {
    if($(this).parent().find('input[type="checkbox"]').is(':checked'))
    {
        $(this).parent().find('input[type="checkbox"]').prop('checked', false);
    }
    else
    {
        $(this).parent().find('input[type="checkbox"]').prop('checked', true);
    }
});

Just to say in my example the situation was a dialog box that then verified the check box before closing dialog. None of above and How to check whether a checkbox is checked in jQuery? and jQuery if checkbox is checked did not appear to work either.

In the end

<input class="cb" id="rd" type="checkbox">
<input class="cb" id="fd" type="checkbox">

var fd=$('.cb#fd').is(':checked');
var rd= $('.cb#rd').is(':checked');

This worked so calling the class then the ID. rather than just the ID. It may be due to the nested DOM elements on this page causing the issue. The workaround was above.


Something like this can help

togglecheckBoxs =  function( objCheckBox ) {

    var boolAllChecked = true;

    if( false == objCheckBox.checked ) {
        $('#checkAll').prop( 'checked',false );
    } else {
        $( 'input[id^="someIds_"]' ).each( function( chkboxIndex, chkbox ) {
            if( false == chkbox.checked ) {
                $('#checkAll').prop( 'checked',false );
                boolAllChecked = false;
            }
        });

        if( true == boolAllChecked ) {
            $('#checkAll').prop( 'checked',true );
        }
    }
}

For checkbox with an id

<input id="id_input_checkbox13" type="checkbox"></input>

you can simply do

$("#id_input_checkbox13").prop('checked')

you will get true or false as return value for above syntax. You can use it in if clause as normal boolean expression.


Toggle checkbox checked

$("#checkall").click(function(){
    $("input:checkbox").prop( 'checked',$(this).is(":checked") );
})

Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!

Here are the syntaxes :

var checkbox = $('#'+id);
/* OR var checkbox = $("input[name=checkbox1]"); whichever is best */

/* The DOM way - The fastest */
if(checkbox[0].checked == true)
   alert('Checkbox is checked!!');

/* Using jQuery .prop() - The second fastest */
if(checkbox.prop('checked') == true)
   alert('Checkbox is checked!!');

/* Using jQuery .is() - The slowest in the lot */
if(checkbox.is(':checked') == true)
   alert('Checkbox is checked!!');

I personally prefer .prop(). Unlike .is(), It can also be used to set the value.


Since it's mid 2019 and jQuery sometimes takes a backseat to things like VueJS, React etc. Here's a pure vanilla Javascript onload listener option:

<script>
  // Replace 'admincheckbox' both variable and ID with whatever suits.

  window.onload = function() {
    const admincheckbox = document.getElementById("admincheckbox");
    admincheckbox.addEventListener('click', function() {
      if(admincheckbox.checked){
        alert('Checked');
      } else {
        alert('Unchecked');
      }
    });
  }
</script>

Using this code you can check at least one checkbox is selected or not in different checkbox groups or from multiple checkboxes. Using this you can not require to remove IDs or dynamic IDs. This code work with the same IDs.

Reference Link

<label class="control-label col-sm-4">Check Box 2</label>
    <input type="checkbox" name="checkbox2" id="checkbox21" value=ck1 /> ck1<br />
    <input type="checkbox" name="checkbox2" id="checkbox22" value=ck2 /> ck2<br />

<label class="control-label col-sm-4">Check Box 3</label>
    <input type="checkbox" name="checkbox3" id="checkbox31" value=ck3 /> ck3<br />
    <input type="checkbox" name="checkbox3" id="checkbox32" value=ck4 /> ck4<br />

<script>
function checkFormData() {
    if (!$('input[name=checkbox2]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
        return false;
    }
    if (!$('input[name=checkbox3]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
        return false;
    }
    alert("Success");
    return true;
}
</script>

use code below

<script>

$(document).ready(function () {
  $("[id$='chkSendMail']").attr("onchange", "ShowMailSection()");
}

function ShowMailSection() {
  if ($("[id$='chkSendMail'][type='checkbox']:checked").length >0){
      $("[id$='SecEmail']").removeClass("Hide");
  }
</script>

참고URL : https://stackoverflow.com/questions/2204250/check-if-checkbox-is-checked-with-jquery

반응형