Programing

확인란이 선택되어 있으면

crosscheck 2020. 7. 8. 07:53
반응형

확인란이 선택되어 있으면


확인란을 선택하면이 확인란을 선택하고 싶습니다 <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
앤디 E를 : 좋은 쓰기까지 우리가 jQuery를 남용하는 경향이 방법을 수행 한 요소의 속성에 액세스에 jQuery를의 굉장한 능력을 활용을 . 물품은 특히 사용 취급 .attr("id")하지만 경우 #checkbox 이다<input type="checkbox" /> 소자 문제에 대해 동일 $(...).attr('checked')(또는 $(...).is(':checked')) 대 this.checked.


이 시도.

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

때때로 우리는 jquery를 과도하게 사용합니다. 일반 자바 스크립트와 함께 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');
});

Probably you can go with this code to take actions as the checkbox is checked or unchecked.

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

I would do :

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

    if(this.checked){

      // Do one thing 

    }

    else{

     // Do some other thing

    }

});

See : https://www.w3schools.com/jsref/prop_checkbox_checked.asp


Optimal implementation

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

Demo

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


Why not use the built in events?

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

반응형