programing

jQuery에서 체크박스가 켜져 있는지 여부를 확인하려면 어떻게 해야 합니까?

sourcetip 2022. 10. 8. 16:03
반응형

jQuery에서 체크박스가 켜져 있는지 여부를 확인하려면 어떻게 해야 합니까?

.checked체크박스의 속성을 지정하고 jQuery를 사용하여 선택한 속성을 기반으로 액션을 수행합니다.

를 들어, " " 가 ,age.age이치노

는 반환됩니다.false★★★★★★★★★★★★★★★★★★:

if ($('#isAgeSelected').attr('checked')) {
  $("#txtAge").show();
} else {
  $("#txtAge").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">
  Age is selected
</div>

수 있을까요?checked★★★★★★★★★★★★★★★★★?

선택한 속성을 쿼리하려면 어떻게 해야 합니까?

checked하면, 「DOM」이라고 하는 「DOM」이 됩니다.checked요소 상태

따라서 기존 코드를 사용하면 다음과 같이 할 수 있습니다.

if(document.getElementById('isAgeSelected').checked) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

단, 다음과 같은 방법으로 보다 예쁜 방법을 사용할 수 있습니다.

$('#isAgeSelected').click(function() {
    $("#txtAge").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>

jQuery 함수 사용:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked

jQuery > 1.6 사용

<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />

// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true

새 속성 방법 사용:

if($('#checkMeOut').prop('checked')) {
    // something when checked
} else {
    // something else when not
}

jQuery 1.6 이상

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

jQuery 1.5 이하

$('#isAgeSelected').attr('checked')

모든 버전의 jQuery

// Assuming an event handler on a checkbox
if (this.checked)

모든 것은 시안의 공이다.

저는 이것을 사용하고 있으며, 이것은 완벽하게 정상적으로 동작하고 있습니다.

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

주의: 체크박스를 켜면 true가 반환됩니다.그렇지 않으면 정의되지 않습니다.따라서 "TRUE" 값을 확인하는 것이 좋습니다.

용도:

<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

$("#planned_checked").change(function() {
    if($(this).prop('checked')) {
        alert("Checked Box Selected");
    } else {
        alert("Checked Box deselect");
    }
});

    $("#planned_checked").change(function() {
        if($(this).prop('checked')) {
            alert("Checked Box Selected");
        } else {
            alert("Checked Box deselect");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

jQuery 1.6 이후 동작은 변경되었으며 사용자는 jQuery 1.6을 사용하여 요소의 체크 상태를 가져오지 않도록 권장합니다.대신 다음을 사용해야 합니다.

$("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
                                        // Return value changes with checkbox state
);

다른 두 가지 가능성이 있습니다.

$("#txtAge").get(0).checked
$("#txtAge").is(":checked")

이 방법은 효과가 있었습니다.

$get("isAgeSelected ").checked == true

서 ★★★★★isAgeSelected아이디

또, @karim79의 답변은 문제 없습니다.내가 그것을 시험했을 때 무엇을 놓쳤는지 확실하지 않다.

주의: 이 답변은 jQuery가 아닌 Microsoft Ajax를 사용합니다.

jquery를 jquery를 ..prop"이것들"은 다음과 같습니다.

$('#isAgeSelected').prop('checked')true 마크가 붙어 있는 경우false체크박스를 끄면 됩니다.확인했고 아까 이 문제를 알게 되었습니다. $('#isAgeSelected').attr('checked') ★★★★★★★★★★★★★★★★★」$('#isAgeSelected').is('checked')undefined같이 하십시오.그래서 아래와 같이 하세요.

if($('#isAgeSelected').prop('checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

용도:

<input type="checkbox" id="abc" value="UDB">UDB
<input type="checkbox" id="abc" value="Prasad">Prasad
$('input#abc').click(function(){
  if($(this).is(':checked'))
  {
    var checkedOne=$(this).val()
    alert(checkedOne);

    // Do some other action
  }
})

이 방법은 체크박스를 끄지 않고 체크박스를 켜야만 필요한 액션을 수행할 수 있도록 하는 경우에 도움이 됩니다.

「 」의 Click는 신뢰할 수 없습니다.은, 「할 수 없다」라고 하는 것입니다.checked이벤트 핸들러를 실행하는 동안 속성이 변경될 수 있습니다.

를 상, 드, 드, 드, 드, 드, 넣는 것이 좋습니다.change이벤트 핸들러(예: 체크박스의 값이 변경될 때마다 기동됩니다).

$('#isAgeSelected').bind('change', function () {

   if ($(this).is(':checked'))
     $("#txtAge").show();
   else
     $("#txtAge").hide();
});

도 한번 드셔보세요.change[ ]를 :checked상태 변화

$("#isAgeSelected").on('change', function() {
  if ($("#isAgeSelected").is(':checked'))
    alert("checked");
  else {
    alert("unchecked");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected" />
<div id="txtAge" style="display:none">
  Age is selected
</div>

나도 똑같은 문제에 부딪혔어.ASP가 있어요.[NET] 체크박스

<asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />

jQuery 코드에서 아래 셀렉터를 사용하여 체크박스가 켜져 있는지 확인해보니 마법처럼 작동하는 것 같습니다.

if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

Css Class 대신 ID를 사용해도 됩니다.

if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

도움이 됐으면 좋겠네요.

저는 jQuery 없이 똑같은 일을 하는 방법에 대한 답변을 올리기로 했습니다.내가 반란군이라고 해서.

var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');

// Just because of IE <333
ageCheckbox.onchange = function() {
    // Check if the checkbox is checked, and show/hide the text field.
    ageInput.hidden = this.checked ? false : true;
};

아이디.onchange 있는지 입니다.hidden연령 텍스트 필드의 속성을 적절히 지정합니다.3번입니다.

여기 그것을 시험해 볼 수 있는 바이올린이 있다.

부록

가 되는 는, 를 합니다.display속성을 none 및 inline으로 설정합니다.

elem.style.display = this.checked ? 'inline' : 'none';

속도는 느리지만 크로스 브라우저 호환.

난 네가 할 수 있다고 믿어.

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}

이 코드가 도움이 됩니다.

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});

이것으로 충분합니다.

/* isAgeSelected being id for checkbox */

$("#isAgeSelected").click(function(){
  $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});

체크박스가 켜져 있는지 여부를 확인하는 방법은 여러 가지가 있습니다.

jQuery를 사용하여 확인하는 방법

if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))

예를 확인하거나 다음 문서를 작성합니다.

이것은 같은 작업을 수행하는 몇 가지 다른 방법입니다.

$(document).ready(function (){

    $('#isAgeSelected').click(function() {
        // $("#txtAge").toggle(this.checked);

        // Using a pure CSS selector
        if ($(this.checked)) {
            alert('on check 1');
        };

        // Using jQuery's is() method
        if ($(this).is(':checked')) {
            alert('on checked 2');
        };

        //  // Using jQuery's filter() method
        if ($(this).filter(':checked')) {
            alert('on checked 3');
        };
    });
});
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>

사용방법:

if ($('input[name="salary_in.Basic"]:checked').length > 0)

체크박스를 켜면 길이가 0보다 커집니다.

내 방법은 다음과 같습니다.

if ( $("#checkbox:checked").length ) {       
    alert("checkbox is checked");
} else {
    alert("checkbox is not checked");
}
$(selector).attr('checked') !== undefined

값은 반환됩니다.true되어 있고, 「」가 되어 있는 ,false그렇지 않다면.

다음을 사용할 수 있습니다.

  if(document.getElementById('isAgeSelected').checked)
    $("#txtAge").show();  
  else
    $("#txtAge").hide();

if($("#isAgeSelected").is(':checked'))
  $("#txtAge").show();  
else
  $("#txtAge").hide();

둘 다 잘 될 거예요.

$(document).ready(function() {    
    $('#agecheckbox').click(function() {
        if($(this).is(":checked"))
        {
            $('#agetextbox').show();
        } else {
            $('#agetextbox').hide();
        }
    });
});

1) HTML 마크업이 다음과 같은 경우:

<input type="checkbox"  />

사용되는 특성:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

소품을 사용하는 경우:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2) HTML 마크업이 다음과 같은 경우:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"

사용되는 특성:

$(element).attr("checked") // Will return checked whether it is checked="true"

사용하는 소품:

$(element).prop("checked") // Will return true whether checked="checked"

이 예는 버튼용입니다.

다음을 시도해 보십시오.

<input type="button" class="check" id="checkall" value="Check All" />  &nbsp; <input type="button" id="remove" value="Delete" /> <br/>

<input type="checkbox" class="cb-element"  value="1" /> Checkbox  1 <br/>
<input type="checkbox" class="cb-element"  value="2" /> Checkbox  2 <br/>
<input type="checkbox" class="cb-element"  value="3" /> Checkbox  3 <br/>


$('#remove').attr('disabled', 'disabled'); 

$(document).ready(function() {  

    $('.cb-element').click(function() {

        if($(this).prop('checked'))
        {
            $('#remove').attr('disabled', false);
        }
        else
        {
            $('#remove').attr('disabled', true);
        }
    });   

    $('.check:button').click(function()
{
    var checked = !$(this).data('checked');
    $('input:checkbox').prop('checked', checked);
    $(this).data('checked', checked);

    if(checked == true)
    {
        $(this).val('Uncheck All');
         $('#remove').attr('disabled', false);
    }

    else if(checked == false)
    {
        $(this).val('Check All');
        $('#remove').attr('disabled', true);
    }
});
});

맨 위의 답변은 나에게 효과가 없었다.하지만, 이것은 다음과 같습니다.

<script type="text/javascript">
    $(document).ready(function(){

        $("#li_13").click(function(){
            if($("#agree").attr('checked')){
                $("#saveForm").fadeIn();
            }
            else
            {
                $("#saveForm").fadeOut();
            }
        });
    });
</script>

하면 #li_13 요소가 #li_13 요소에서 #agree(동의)를 됩니다..attr('checked') #하고 페이드아웃하지 요소를 합니다.페이드인 경우 #saveForm 요소를 입력하고 페이드인 경우 saveForm 요소를 페이드아웃합니다.

사용하고 있습니다.

 <input type="checkbox" id="isAgeSelected" value="1" /> <br/>
 <input type="textbox" id="txtAge" />

 $("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();

했습니다(「JavaScript」를 ).textboxcheckboxchecked), 문제는 css만으로 해결할 수 있습니다.이 방법을 사용하면 JavaScript를 사용하지 않도록 설정한 사용자에게 양식이 적용됩니다.

다음의 HTML 가 있는 것을 전제로 합니다.

<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />

다음의 CSS 를 사용하고, 필요한 기능을 실현할 수 있습니다.

 #show_textbox:not(:checked) + input[type=text] {display:none;}

다른 시나리오에서는 적절한 CSS 실렉터를 생각할 수 있습니다.

접근방식을 설명하기 위한 바이올린입니다.

클릭 시 체크박스가 켜지거나 꺼진 경우 작업을 수행합니다.

$('#customCheck1').click(function() {
  if (this.checked) {
    console.log('checked');
  } else {
    console.log('un-checked');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

편집: 좋은 프로그래밍 표현이 아닙니다.if (boolean == true)그래도.checked속성이 다른 유형 변수도 반환할 수 있습니다.

사용하는 것이 좋다.prop("checked")되돌아오다true ★★★★★★★★★★★★★★★★★」falsedisclossible.

언급URL : https://stackoverflow.com/questions/901712/how-do-i-check-whether-a-checkbox-is-checked-in-jquery

반응형