Make input section required when both checkboxes are selected

前端 未结 3 1092
孤城傲影
孤城傲影 2021-01-29 09:11

So I have two checkboxes when clicked separately, will make the bottom section required - How can I make it that the last section is required when both are checked? I can\'t see

相关标签:
3条回答
  • 2021-01-29 09:17

    LOL, didn't I say to only use one $(document).ready() function?

    Anyway, just combine the two conditionals into a third change function.

    /* Make checkbox textboxes not required unless checked */
    $(document).ready(function() {
        $('#rtd3Transaction').change(function() {
            if ($('.rtdConfirm').attr('required')) {
                $('.rtdConfirm').removeAttr('required');
            }
            else {
                $('.rtdConfirm').attr('required','required');
            }
        });
    
        $('#rtd3Device').change(function() {
            if ($('.rtdConfirm').attr('required')) {
                $('.rtdConfirm').removeAttr('required');
            }
            else {
                $('.rtdConfirm').attr('required','required');
            }
        });
    
        $('#rtd3Transaction, #rtd3Device').change(function() {
            if ($('#rtd3Transaction').checked && $('#rtd3Transaction').checked) {
                $('.rtdConfirm').attr('required','required');
            }
            else {
                $('.rtdConfirm').removeAttr('required');
            }
        });
    });
    

    If that doesn't work, post the rest of your code and I'll see what I can do.

    0 讨论(0)
  • 2021-01-29 09:29

    In JS you may use the onchange event on the parent that holds the check boxes, hopefully a form, and check if both check boxes are checked, if they do set the third check box to required

    const rtd3Transaction = document.querySelector('#rtd3Transaction');
    const rtd3Device = document.querySelector('#rtd3Device');
    const rtdConfirm = document.querySelector('#rtdConfirm');
    
    document.querySelector('form').addEventListener('change', ()=> {
      if(rtd3Transaction.checked && rtd3Device.checked) {
        rtdConfirm.required = true;
      }
    })
    
    0 讨论(0)
  • 2021-01-29 09:35

    I see you're using jQuery, so here's a jQuery-based solution.

    First, you can combine the change event handler for both inputs.

    Second, you can use .prop("checked") to find the checked state of your checkboxes.

    Finally, use .prop("required", true/false) to set the required state of your last checkbox.

    Here's how I went about it:

    $(document).ready(function()
    {
        $("#rtd3Transaction, #rtd3Device").change(function()
        {
            var required = $("#rtd3Transaction").prop("checked") && $("#rtd3Device").prop("checked");
            $(".rtdConfirm").prop("required", required);
        });
    });
    
    0 讨论(0)
提交回复
热议问题