JavaScript 체크박스를 켜거나 끄다
JavaScript를 사용하여 체크박스를 켜거나 끄려면 어떻게 해야 합니까?
Javascript:
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jQuery (1.6+):
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jQuery (1.5-):
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
아직 언급되지 않은 중요한 행동:
선택된 속성을 프로그래밍 방식으로 설정해도 확인란의 이벤트는 실행되지 않습니다.
으로 직접 :
http://jsfiddle.net/fjaeger/L9z9t04p/4/httpjsfiddle.net/fjaeger//4/
(Chrome 46, Firefox 41 및 IE 11에서 테스트된 피들)
방법
언젠가 당신은 해고되는 이벤트에 의존하는 코드를 작성하는 자신을 발견할 것이다.기동하고 있는 하려면 , 「」를 호출합니다.click()
체크박스 요소의 메서드는 다음과 같습니다.
document.getElementById('checkbox').click();
이 있는 으로 [Da], [Do's ], [Do's ], [Do's ], [Do's ], [Do's ], [Do's ], [Do's ]로 설정되는 것이 [Do']체크박스의 체크박스의 상태가 .true
★★★★★★★★★★★★★★★★★」false
「 」는, 「 」에해 주세요.change
이벤트는 체크된 속성이 실제로 변경되었을 때만 발생합니다.
됩니다.jQuery를 사용하여 합니다.쿼리:prop
★★★★★★★★★★★★★★★★★」attr
,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,change
★★checked
해 볼 수 요.checked
Atribute를 Atribute를 합니다.click()
§:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
클릭 방법에 대한 자세한 내용은 여기를 참조하십시오.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/clickhttpsdeveloper.mozilla.org/en-US/docs/Web/API//click
확인 대상:
document.getElementById("id-of-checkbox").checked = true;
끄려면:
document.getElementById("id-of-checkbox").checked = false;
다음과 같이 미립자 체크박스를 켤 수 있습니다.
$('id of the checkbox')[0].checked = true
에 의해 꺼집니다.
$('id of the checkbox')[0].checked = false
시험:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');
주의: '체크된' 속성을 비어 있지 않은 문자열로 설정하면 체크박스가 켜집니다.
따라서 "체크된" 속성을 "false"로 설정하면 확인란이 선택됩니다.체크박스를 끄려면 값을 빈 문자열, null 또는 부울 값 false로 설정해야 합니다.
바닐라 js 사용:
//for one element:
document.querySelector('.myCheckBox').checked = true //will select the first matched element
document.querySelector('.myCheckBox').checked = false//will unselect the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
//iterating over all matched elements
checkbox.checked = true //for selection
checkbox.checked = false //for unselection
}
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
싱글 체크 시행의 경우
myCheckBox.checked=1
<input type="checkbox" id="myCheckBox"> Call to her
멀티트라이용
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
Buy wine: <input type="checkbox" class="imChecked"><br>
Play smooth-jazz music: <input type="checkbox"><br>
Shave: <input type="checkbox" class="imChecked"><br>
어떤 이유로 체크박스 요소에서 를 실행하고 싶지 않은 경우(또는 실행할 수 없는 경우) 해당 .checked 속성(의 IDL 속성)을 통해 해당 값을 직접 변경할 수 있습니다.
이렇게 해도 정상적으로 관련된 이벤트(변경)는 실행되지 않으므로 관련된 이벤트 핸들러와 함께 작동하는 완전한 솔루션을 얻으려면 수동으로 실행해야 합니다.
다음은 raw javascript(ES6)의 기능 예입니다.
class ButtonCheck {
constructor() {
let ourCheckBox = null;
this.ourCheckBox = document.querySelector('#checkboxID');
let checkBoxButton = null;
this.checkBoxButton = document.querySelector('#checkboxID+button[aria-label="checkboxID"]');
let checkEvent = new Event('change');
this.checkBoxButton.addEventListener('click', function() {
let checkBox = this.ourCheckBox;
//toggle the checkbox: invert its state!
checkBox.checked = !checkBox.checked;
//let other things know the checkbox changed
checkBox.dispatchEvent(checkEvent);
}.bind(this), true);
this.eventHandler = function(e) {
document.querySelector('.checkboxfeedback').insertAdjacentHTML('beforeend', '<br />Event occurred on checkbox! Type: ' + e.type + ' checkbox state now: ' + this.ourCheckBox.checked);
}
//demonstration: we will see change events regardless of whether the checkbox is clicked or the button
this.ourCheckBox.addEventListener('change', function(e) {
this.eventHandler(e);
}.bind(this), true);
//demonstration: if we bind a click handler only to the checkbox, we only see clicks from the checkbox
this.ourCheckBox.addEventListener('click', function(e) {
this.eventHandler(e);
}.bind(this), true);
}
}
var init = function() {
const checkIt = new ButtonCheck();
}
if (document.readyState != 'loading') {
init;
} else {
document.addEventListener('DOMContentLoaded', init);
}
<input type="checkbox" id="checkboxID" />
<button aria-label="checkboxID">Change the checkbox!</button>
<div class="checkboxfeedback">No changes yet!</div>
이 기능을 실행하고 체크박스와 버튼을 모두 클릭하면 어떻게 동작하는지 알 수 있습니다.
제가 문서를 사용한 것에 주의해 주세요.Query Selector는 간결함/간단함이지만, 이것은 컨스트럭터에게 주어진 ID를 전달하거나 체크박스의 아리아라벨로 기능하는 모든 버튼에 쉽게 적용될 수 있습니다(버튼에 ID를 설정하고 체크박스에 아리아라벨을 부여하지 않아도 됩니다).다른 방법으로 확장해야 합니다.마지막 두 개addEventListener
는, 동작의 데모에 지나지 않습니다.
현재의 답변에는 동의하지만, 제 경우에는 이 코드가 향후에 도움이 되었으면 합니다.
// check
$('#checkbox_id').click()
언급URL : https://stackoverflow.com/questions/8206565/check-uncheck-checkbox-with-javascript
'source' 카테고리의 다른 글
왜 사람들은 json 응답 앞에 "1; " 및 "for(;;)"와 같은 코드를 넣을까요? (0) | 2022.09.08 |
---|---|
Mariadb 연결 클라이언트:mysql 8.0에서 사용자(암호: NO 사용)에 대한 액세스가 거부되었습니다. (0) | 2022.09.08 |
크롬 및 파이어폭스의 Javascript에서 Cryptic "스크립트 오류"가 보고됨 (0) | 2022.09.08 |
스파크 오류 - 지원되지 않는 클래스 파일의 줄자 버전 (0) | 2022.09.08 |
테이블 내의 각 외부 키 ID 인스턴스 수를 카운트하려면 어떻게 해야 합니까? (0) | 2022.09.08 |