[javascript] jQuery 체크 박스 변경 및 클릭 이벤트

$(document).ready(function() {
  //set initial state.
  $('#textbox1').val($(this).is(':checked'));

  $('#checkbox1').change(function() {
    $('#textbox1').val($(this).is(':checked'));
  });

  $('#checkbox1').click(function() {
    if (!$(this).is(':checked')) {
      return confirm("Are you sure?");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox1"/><br />
<input type="text" id="textbox1"/>

여기서는 .change()텍스트 상자 값을 확인란 상태로 업데이트합니다. .click()선택을 취소 할 때 작업을 확인하는 데 사용 합니다. 사용자가 취소를 선택하면 .change()확인 표시가 복원되지만 확인 전에 실행됩니다.

그러면 일관된 상태가 유지되지 않으며 확인란을 선택하면 텍스트 상자에 false가 표시됩니다.

취소를 처리하고 텍스트 상자 값을 확인 상태와 일치하게 유지하려면 어떻게합니까?



답변

JSFiddle 에서 테스트되었으며 원하는 것을 수행합니다.이 방법은 확인란과 관련된 레이블을 클릭하면 발생하는 이점이 있습니다.

업데이트 된 답변 :

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val(this.checked);

    $('#checkbox1').change(function() {
        if(this.checked) {
            var returnVal = confirm("Are you sure?");
            $(this).prop("checked", returnVal);
        }
        $('#textbox1').val(this.checked);
    });
});

원래 답변 :

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val($(this).is(':checked'));

    $('#checkbox1').change(function() {
        if($(this).is(":checked")) {
            var returnVal = confirm("Are you sure?");
            $(this).attr("checked", returnVal);
        }
        $('#textbox1').val($(this).is(':checked'));
    });
});


답변

데모

사용하다 mousedown

$('#checkbox1').mousedown(function() {
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
});


답변

을 사용하면 대부분의 답변이 (아마도) 그것을 잡지 못합니다 <label for="cbId">cb name</label>. 즉, 레이블을 클릭하면 확인란을 직접 클릭하지 않고 확인란을 선택합니다. (정확한 질문은 아니지만 다양한 검색 결과가 여기에 오는 경향이 있습니다)

<div id="OuterDivOrBody">
    <input type="checkbox" id="checkbox1" />
    <label for="checkbox1">Checkbox label</label>
    <br />
    <br />
    The confirm result:
    <input type="text" id="textbox1" />
</div>

이 경우 다음을 사용할 수 있습니다.

Earlier versions of jQuery:

$('#OuterDivOrBody').delegate('#checkbox1', 'change', function () {
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

jQuery 1.6.4를 사용한 JSFiddle 예제

jQuery 1.7+

$('#checkbox1').on('change', function() {
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

최신 jQuery 2.x를 사용한 JSFiddle 예제

  • 클릭 가능한 확인란 레이블이있는 HTML 예제 및 HTML 추가

답변

음 .. 두통을 줄이기 위해 (자정이 지난 자정), 나는 생각해 낼 수 있습니다.

$('#checkbox1').click(function() {
  if (!$(this).is(':checked')) {
    var ans = confirm("Are you sure?");
     $('#textbox1').val(ans);
  }
});

그것이 도움이되기를 바랍니다.


답변

나를 위해 이것은 훌륭하게 작동합니다.

$('#checkboxID').click(function () {
    if ($(this).attr('checked')) {
        alert('is checked');
    } else {
        alert('is not checked');
    }
})


답변

여기 있어요

HTML

<input id="ProductId_a183060c-1030-4037-ae57-0015be92da0e" type="checkbox" value="true">

자바 스크립트

<script>
    $(document).ready(function () {

      $('input[id^="ProductId_"]').click(function () {

        if ($(this).prop('checked')) {
           // do what you need here     
           alert("Checked");
        }
        else {
           // do what you need here         
           alert("Unchecked");
        }
      });

  });
</script>


답변

변경 이벤트를 제거하고 대신 클릭 이벤트에서 텍스트 상자의 값을 변경하십시오. 확인 결과를 반환하는 대신 var에서 확인하십시오. 참이면 값을 변경하십시오. 그런 다음 var를 반환하십시오.