etc./StackOverFlow

jQuery에서 확인란이 선택되어 있는지 어떻게 확인합니까?

청렴결백한 만능 재주꾼 2021. 9. 30. 00:21
반응형

질문자 :Community Wiki


나는 확인해야합니다 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 요소의 checked 속성은 요소의 checked 상태를 제공합니다.

기존 코드가 주어지면 다음과 같이 할 수 있습니다.

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

toggle 사용하여 이를 수행하는 훨씬 더 예쁜 방법이 있습니다.

 $('#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>


Community Wiki

jQuery의 is() 함수 사용:

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

Community Wiki

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 }

Community Wiki

제이쿼리 1.6+

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

jQuery 1.5 이하

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

모든 버전의 jQuery

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

모든 크레딧은 시안 에게 돌아갑니다.


Community Wiki

나는 이것을 사용하고 있으며 이것은 절대적으로 잘 작동합니다.

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

참고: 확인란을 선택하면 그렇지 않으면 정의되지 않은 true를 반환하므로 "TRUE" 값을 확인하는 것이 좋습니다.


Community Wiki

사용하다:

 <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


Community Wiki

jQuery 1.6부터 jQuery.attr() 의 동작이 변경되었으며 사용자는 요소의 확인 상태를 검색하는 데 사용하지 않는 것이 좋습니다. jQuery.prop() 을 사용해야 합니다.

 $("#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")

Community Wiki

이것은 나를 위해 일했습니다.

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

여기서 isAgeSelected 는 컨트롤의 ID입니다.

또한 @ karim79의 답변 이 잘 작동합니다. 내가 그것을 테스트 할 때 내가 놓친 것이 무엇인지 확실하지 않습니다.

참고로 이것은 jQuery가 아닌 Microsoft Ajax를 사용하는 답변입니다.


Community Wiki

업데이트된 버전의 jquery를 사용하는 경우 문제를 해결하려면 .prop

$('#isAgeSelected').prop('checked') 는 선택하면 true , 선택하지 않으면 false 나는 그것을 확인했고 나는이 문제를 더 일찍 발견했습니다. $('#isAgeSelected').attr('checked')$('#isAgeSelected').is('checked') 상황에 대한 합당한 답변이 아닌 undefined 를 반환합니다. 그래서 아래와 같이 합니다.

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

도움이 되길 바랍니다 :)- 감사합니다.


Community Wiki

사용하다:

 <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 } })

이것은 체크를 제거할 때가 아니라 체크박스를 체크할 때만 필요한 작업을 수행하도록 하려는 경우에 도움이 될 수 있습니다.


Community Wiki

이벤트 핸들러 자체를 실행하는 동안 checked 속성이 변경될 수 있으므로 확인란 속성에 대해 Click 이벤트 핸들러를 사용하는 것은 신뢰할 수 없습니다!

이상적으로는 확인란의 값이 변경될 때마다 실행되는 것처럼 change 이벤트 핸들러에 코드를 넣는 것이 좋습니다 (변경 방법에 관계없이).

 $('#isAgeSelected').bind('change', function () { if ($(this).is(':checked')) $("#txtAge").show(); else $("#txtAge").hide(); });

Community Wiki

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; };

먼저 ID로 두 요소를 모두 가져옵니다. 그런 다음 확인란의 onchange 이벤트에 확인란이 선택되었는지 확인하고 hidden 속성을 적절하게 설정하는 기능을 할당합니다. 이 예에서는 삼항 연산자를 사용합니다.

테스트할 수 있는 바이올린이 있습니다.

부록

브라우저 간 호환성이 문제라면 CSS display 속성을 noneinline 으로 설정할 것을 제안합니다.

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

느리지만 브라우저 간 호환이 가능합니다.


Community Wiki

나는 당신이 이것을 할 수 있다고 믿습니다:

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

Community Wiki

나는 똑같은 문제에 부딪쳤다. ASP.NET 확인란이 있습니다.

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

jQuery 코드에서 다음 선택기를 사용하여 확인란이 선택되었는지 여부를 확인했는데 매력처럼 작동하는 것 같습니다.

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

CssClass 대신 ID를 사용할 수도 있습니다.

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

도움이 되기를 바랍니다.


Community Wiki

이 코드는 당신을 도울 것입니다

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

Community Wiki

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>


Community Wiki

이것은 나를 위해 작동합니다.

 /* isAgeSelected being id for checkbox */ $("#isAgeSelected").click(function(){ $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide(); });

Community Wiki

확인란이 선택되어 있는지 확인하는 방법에는 여러 가지가 있습니다.

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

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

예를 확인하거나 다음을 문서화하십시오.


Community Wiki

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

 $(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>


Community Wiki

이것을 사용하십시오:

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

확인란을 선택하면 길이가 0보다 큽니다.


Community Wiki

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

 if ( $("#checkbox:checked").length ) { alert("checkbox is checked"); } else { alert("checkbox is not checked"); }

Community Wiki

$(selector).attr('checked') !== undefined

입력이 확인되면 true 반환하고 false 반환합니다.


Community Wiki

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

Community Wiki

당신이 사용할 수있는:

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

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

둘 다 작동해야 합니다.


Community Wiki

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"

Community Wiki

이 예제는 버튼에 대한 것입니다.

다음을 시도하십시오.

 <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); } }); });

Community Wiki

최고 답변은 나를 위해하지 않았습니다. 그래도 다음과 같이 했습니다.

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

.attr('checked') 함수를 사용하여 요소 # 동의(체크박스)가 체크되어 있는지 확인합니다. 그런 다음 #saveForm 요소를 페이드인하고 그렇지 않은 경우 saveForm 요소를 페이드아웃합니다.


Community Wiki

나는 이것을 사용하고 있습니다 :

 <input type="checkbox" id="isAgeSelected" value="1" /> <br/> <input type="textbox" id="txtAge" /> $("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();

Community Wiki

문제에 대한 JavaScript 솔루션을 제안했지만( checkboxchecked 되면 textbox 표시) 이 문제는 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 선택기를 생각할 수 있습니다.

다음은 이 접근 방식을 보여주는 Fiddle 입니다.


Community Wiki

토글: 0/1 또는 기타

 <input type="checkbox" id="nolunch" /> <input id="checklunch />" $('#nolunch').change(function () { if ($(this).is(':checked')) { $('#checklunch').val('1'); }; if ($(this).is(':checked') == false) { $('#checklunch').val('0'); }; });

Community Wiki

출처 : 여기를 클릭하세요


출처 : http:www.stackoverflow.com/questions/901712/how-do-i-check-whether-a-checkbox-is-checked-in-jquery

반응형