Programming

JavaScript (jQuery 또는 Vanilla)로 확인란을 선택 / 선택 취소 하시겠습니까?

procodes 2020. 2. 14. 23:53
반응형

JavaScript (jQuery 또는 Vanilla)로 확인란을 선택 / 선택 취소 하시겠습니까?


JavaScript, jQuery 또는 바닐라를 사용하여 확인란을 선택 / 선택 취소 할 수 있습니까?


자바 스크립트 :

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

아직 언급되지 않은 중요한 행동 :

checked 속성을 프로그래밍 방식으로 설정하면 change확인란 이벤트가 발생하지 않습니다 .

이 바이올린에서 직접보십시오 :
http://jsfiddle.net/fjaeger/L9z9t04p/4/

(Chrome 46, Firefox 41 및 IE 11에서 바이올린 테스트)

click()방법

언젠가는 코드가 작성되는 것을 발견 할 수 있는데, 이는 발생하는 이벤트에 의존합니다. 이벤트가 발생하는지 확인하려면 click()다음과 같이 checkbox 요소 메소드를 호출하십시오 .

document.getElementById('checkbox').click();

그러나,이 대신 구체적으로 설정하는 체크 박스의 체크 상태를 전환 true하거나 false. 기억 그 change이벤트해야에만 화재, checked 속성이 실제로 변경됩니다.

사용하여 속성을 설정 : 또한 jQuery를 방법에 적용 prop하거나 attr화재하지 않는 change이벤트.

checked특정 값으로 설정

메소드 checked를 호출하기 전에 속성을 테스트 할 수 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/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

'checked'속성을 비어 있지 않은 문자열로 설정하면 확인란이 선택됩니다.

따라서 'checked'속성을 "false" 로 설정하면 확인란이 선택됩니다. 확인란을 선택하지 않도록 값을 빈 문자열, null 또는 부울 값 false 로 설정해야했습니다.


이 시도:

//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');

//UnCheck
document.getElementById('chk').removeAttribute('checked');

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

function setCheckboxValue(checkbox,value) {
    if (checkbox.checked!=value)
        checkbox.click();
}

어떤 이유로, 당신이 원하지 않는 (또는 할 수없는)을 실행하면 .click()체크 박스 요소에, 당신은 단순히 .checked를 재산 (AN 통해 직접 값을 변경할 수 있습니다 IDL 속성<input type="checkbox">).

참고 이렇게하면 일반적으로 관련 이벤트 (발생하지 않는 변화를 당신은 완벽한 솔루션을 가지고 수동으로 발사해야합니다 그래서) 그 모든 관련 이벤트 핸들러와 함께 작동합니다.

다음은 원시 자바 스크립트 (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>

이것을 실행하고 확인란과 버튼을 모두 클릭하면 이것이 어떻게 작동하는지 이해할 수 있습니다.

간결함 / 단순성을 위해 document.querySelector를 사용했지만 주어진 ID를 생성자에 전달하거나 확인란의 aria-labels 역할을하는 모든 버튼에 쉽게 적용 할 수 있습니다. 버튼에 ID를 설정하고 확인란에 aria-labelledby를 지정하지 않았습니다.이 방법을 사용하는 경우 수행해야합니다) 또는 다른 방법으로 확장 할 수 있습니다. 마지막 두 가지는 addEventListener작동 방식을 시연하는 것입니다.

참고 : https://stackoverflow.com/questions/8206565/check-uncheck-checkbox-with-javascript-jquery-or-vanilla



반응형