itsource

확인란을 선택한 경우 이 작업을 수행합니다.

mycopycode 2023. 7. 31. 21:22
반응형

확인란을 선택한 경우 이 작업을 수행합니다.

확인란을 선택하면 확인란을 설정합니다.<p> #0099ff.

확인란의 선택을 취소하면 해당 확인란을 실행 취소합니다.

내가 지금까지 가지고 있는 코드:

$('#checkbox').click(function(){
    if ($('#checkbox').attr('checked')) {
        /* NOT SURE WHAT TO DO HERE */
    }
}) 

나는 사용할 입니다. .change()그리고.this.checked:

$('#checkbox').change(function(){
    var c = this.checked ? '#f00' : '#09f';
    $('p').css('color', c);
});

--

사용 시this.checked
Andy E는 jQuery를 과도하게 사용하는 경향에 대해 매우 잘 설명했습니다.jQuery놀라운 성능을 활용하여 요소의 속성에 액세스합니다.이 문서에서는 다음의 사용에 대해 구체적으로 다..attr("id")하지만 그 경우에는#checkbox 이다.<input type="checkbox" />요소 문제가 다음과 같습니다.$(...).attr('checked')(또는 짝수)$(...).is(':checked')) vs.this.checked.

이거 먹어봐요.

$('#checkbox').click(function(){
    if (this.checked) {
        $('p').css('color', '#0099ff')
    }
}) 

가끔 우리는 농담을 너무 많이 합니다.jquery를 플레인 자바스크립트와 함께 사용하면 많은 것을 얻을 수 있습니다.

"this.checked"가 항상 "on"일 수 있습니다.따라서 다음을 권장합니다.

$('#checkbox').change(function() {
  if ($(this).is(':checked')) {
    console.log('Checked');
  } else {
    console.log('Unchecked');
  }
});

클래스를 다른 색상으로 정의한 다음 클래스를 전환하는 것이 좋습니다.

$('#checkbox').click(function(){
    var chk = $(this);
    $('p').toggleClass('selected', chk.attr('checked'));
}) 

이런 식으로 코드는 모든 CSS 속성을 지정할 필요가 없기 때문에 더 깨끗합니다(예: 테두리, 텍스트 스타일 또는 기타...). 하지만 클래스를 전환하면 됩니다.

확인란이 선택되지 않았거나 선택되지 않은 문제를 처리하기 위한 미친 해결책을 발견했습니다. 여기 제 알고리즘이 있습니다.전역 변수를 생성합니다. 예를 들어 var check_holder라고 합니다.

check_holder는 3개의 상태를 가집니다.

  1. 정의되지 않은 상태
  2. 0 상태
  3. 1개의

확인란을 클릭하면

$(document).on("click","#check",function(){
    if(typeof(check_holder)=="undefined"){
          //this means that it is the first time and the check is going to be checked
          //do something
          check_holder=1; //indicates that the is checked,it is in checked state
    }
    else if(check_holder==1){
          //do something when the check is going to be unchecked
          check_holder=0; //it means that it is not checked,it is in unchecked state
    }
     else if(check_holder==0){
            //do something when the check is going to be checked
            check_holder=1;//indicates that it is in a checked state
     }
});

위의 코드는 여러 상황에서 확인란이 선택되었는지 여부를 확인하는 데 사용할 수 있습니다.그 뒤에 있는 개념은 확인란 상태를 변수에 저장하는 것입니다. 즉, 확인란 상태가 켜져 있을 때 꺼집니다. 이 논리를 사용하여 문제를 해결할 수 있기를 바랍니다.

다음 코드 확인:

<!-- script to check whether checkbox checked or not using prop function -->
<script>
$('#change_password').click(function(){
    if($(this).prop("checked") == true){ //can also use $(this).prop("checked") which will return a boolean.
        alert("checked");
    }
    else if($(this).prop("checked") == false){
        alert("Checkbox is unchecked.");
    }
});
</script>
$('#checkbox').change(function(){
   (this.checked)?$('p').css('color','#0099ff'):$('p').css('color','another_color');
});

이 코드를 사용하여 확인란이 선택되어 있거나 선택되지 않은 경우 액션을 수행할 수 있습니다.

$('#chk').on('click',function(){
    if(this.checked==true){
      alert('yes');
    }else{
      alert('no');
    }
});

제가 할게요.

$('#checkbox').on("change", function (e){ 

    if(this.checked){

      // Do one thing 

    }

    else{

     // Do some other thing

    }

});

참조: https://www.w3schools.com/jsref/prop_checkbox_checked.asp

최적의 구현

$('#checkbox').on('change', function(){
    $('p').css('color', this.checked ? '#09f' : '');
});

데모

$('#checkbox').on('change', function(){
    $('p').css('color', this.checked ? '#09f' : '');
});
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input id="checkbox" type="checkbox" /> 
<p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
    eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<p>
    Ut enim ad minim veniam, quis nostrud exercitation ullamco
    laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu
    fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est
    laborum.
</p>

기본 제공 이벤트를 사용하는 것은 어떻습니까?

$('#checkbox').click(function(e){
    if(e.target.checked) {
     // code to run if checked
        console.log('Checked');

     } else {

     //code to run if unchecked
        console.log('Unchecked');
     }
});

언급URL : https://stackoverflow.com/questions/4243554/if-checkbox-is-checked-do-this

반응형