4

Is it possible to make the fields required only when I have the checkboxes checked? Below is what I attempted but I can't seem to get it to work.

So I want to be able to have the field 1 and two only required when the checkboxes are checked on either.

I've attempted the below Javascript code but I can't seem to get it to work properly.

let toggleInputRequired = ( checkbox, input ) => {
    checkbox.addEventListener( 'change', e => {
        if ( e.currentTarget.checked )
            input.setAttribute( 'required', 'required' );
        else
            input.removeAttribute( 'required' );
    } );

    checkbox.onchange();
}

toggleInputRequired( document.querySelector( 'input[name="rtk[checked][]"]' ), document.querySelector( 'input[name="rtk[5][field1]"]' ) );

enter image description here

/* Resident Selection for Alert */
document.getElementById('resident').addEventListener('change', function() {
    if (this.value !== 'CA') {
        document.getElementById('stateWarning').style.display = 'block';
        document.querySelector('#stateWarning b#stateName').textContent = this.options[this.selectedIndex].text;
    } else {
        document.getElementById('stateWarning').style.display = 'none';
    }
});

/* Right to Know */
const formWrapperPersonal = document.getElementById('form-wrapper-personal');
const formWrapperSpecific = document.getElementById('form-wrapper-specific');

document.getElementById('rtk1').addEventListener('change', (e) => {
    if (e.target.checked) {
        formWrapperPersonal.style.display = ''
    } else {
        formWrapperPersonal.style.display = 'none'
    }
});

document.getElementById('rtk5').addEventListener('change', (e) => {
    if (e.target.checked) {
        formWrapperSpecific.style.display = ''
    } else {
        formWrapperSpecific.style.display = 'none'
    }
});

/* Right to Delete */
const formWrapperCertainSelection = document.getElementById('form-wrapper-certain-selection');

const toggleCertainForm = () => {
    const formWrapper = document.getElementById('form-wrapper-certain');
    const rtd3 = document.getElementById('rtd3');
    formWrapper.style.display = rtd3.checked ? '' : 'none';
};

document.querySelectorAll('[name="rtd[checked]"]').forEach(r =>
    r.addEventListener('change', toggleCertainForm)
);

document.getElementById('rtd3Transaction').addEventListener('change', (e) => {
    if (e.target.checked || document.getElementById("rtd3Device").checked) {
        formWrapperCertainSelection.style.display = ''
    } else {
        formWrapperCertainSelection.style.display = 'none'
    }
});

document.getElementById('rtd3Device').addEventListener('change', (e) => {
    if (e.target.checked || document.getElementById("rtd3Transaction").checked) {
        formWrapperCertainSelection.style.display = ''
    } else {
        formWrapperCertainSelection.style.display = 'none'
    }
});
<?php require_once 'classes/autoload.php'; ?>
<?php require_once 'templates/header.php'; ?>

<!-- needs-validation -->
<form class="needs-validation" id="contactForm" action="/" method="post" novalidate>
    <div class="row mt-3">
        <div class="col-md">
            <label for="resident">I am a resident of:</label>
            <select class="custom-select" id="resident" required>
                <option value="">Choose...</option>
                <?php foreach (Vars::states() as $abbr => $state): ?>
                    <option value="<?= $abbr; ?>"><?= $state; ?></option>
                <?php endforeach; ?>
            </select>
            <div class="invalid-feedback">
                Select state of residence.
            </div>
        </div>
    </div>

    <h5 class="mt-4">Right to Know</h5>
    <div>
        You have the right to request that <?= $config->get_company(); ?> disclose to you certain information about our collection, use and disclosure of your personal information within the preceding 12 months. Please check the box(es) below relating to the information you would like <?= $config->get_company(); ?> to disclose to you:
    </div>
    <div class="custom-control custom-switch mt-3">
        <input type="checkbox" class="custom-control-input" id="rtk1" name="rtk[checked][]" value="1">
        <label class="custom-control-label" for="rtk1">The categories of personal information <?= $config->get_company(); ?> has collected about you.</label>
    </div>
    <div id='form-wrapper-personal' style="display:none">
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <div class="col-sm-11">
                <i>Please provide the following information to be used for verification purposes:</i>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <label for="rtk1Field1" class="col-sm-2 col-form-label">Field 1</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" id="rtk1Field1" name="rtk[1][field1]" required>
                <div class="invalid-feedback">
                    Field 1 is required.
                </div>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <label for="rtk1Field2" class="col-sm-2 col-form-label">Field 2</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" id="rtk1Field2" name="rtk[1][field2]" required>
                <div class="invalid-feedback">
                    Field 2 is required.
                </div>
            </div>
        </div>
    </div>
    <div class="custom-control custom-switch mt-3">
        <input type="checkbox" class="custom-control-input" id="rtk5" name="rtk[checked][]" value="5">
        <label class="custom-control-label" for="rtk5">The specific pieces of personal information <?= $config->get_company(); ?> has collected about you.</label>
    </div>
    <div id='form-wrapper-specific' style="display:none">
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <div class="col-sm-11">
                <i>Please provide the following information to be used for verification purposes:</i>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <label for="rtk5Field1" class="col-sm-2 col-form-label">Field 1</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" id="rtk5Field1" name="rtk[5][field1]" required>
                <div class="invalid-feedback">
                    Field 1 is required.
                </div>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <label for="rtk5Field2" class="col-sm-2 col-form-label">Field 2</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" id="rtk5Field2" name="rtk[5][field2]" required>
                <div class="invalid-feedback">
                    Field 2 is required.
                </div>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <label for="rtk5Field3" class="col-sm-2 col-form-label">Field 3</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" id="rtk5Field3" name="rtk[5][field3]" required>
                <div class="invalid-feedback">
                    Field 3 is required.
                </div>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <div class="col-sm-11">
                <i>To request access to the specific pieces of personal information <?= $config->get_company(); ?> has collected about you, you are required to sign a declaration, under penalty of perjury, that you are the individual whose information is provided above. Please <a href="<?= Path::file('sample.pdf'); ?>" target="_blank">download the declaration form</a> and upload a completed and signed copy below. If you do not submit the form, we will not be able to provide you with the specific pieces of personal information <?= $config->get_company(); ?> has collected about you.</i>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <div class="col-sm-11">
                <div class="custom-file">
                    <input type="file" class="custom-file-input" id="rtk5Declaration"  name="rtk[5][file]" required>
                    <label class="custom-file-label" for="rtk5Declaration">Upload declaration form</label>
                    <div class="invalid-feedback">
                        Upload completed and signed declaration form.
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id='form-wrapper-certain' style="display:none">
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <div class="col-sm-11">
                <i>You must specify the personal information you would like us to delete:</i>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <div class="col-sm-11">
                <div class="custom-control custom-switch">
                    <input type="checkbox" class="custom-control-input" id="rtd3Transaction" name="rtd[3][transaction]">
                    <label class="custom-control-label" for="rtd3Transaction">My transaction data</label>
                </div>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-sm-1"></div>
            <div class="col-sm-11">
                <div class="custom-control custom-switch">
                    <input type="checkbox" class="custom-control-input" id="rtd3Device" name="rtd[3][device]">
                    <label class="custom-control-label" for="rtd3Device">Information about my device(s) collected through cookies and other automated collection tools</label>
                </div>
            </div>
        </div>
        <div id='form-wrapper-certain-selection' style="display: none;">
            <div class="row mt-3">
                <div class="col-sm-2"></div>
                <div class="col-sm-10">
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="rtdConfirm" name="rtd[confirm]" required>
                        <label class="custom-control-label" for="rtdConfirm">I confirm that I would like FleishmanHillard not to sell your personal information to third parties.</label>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md">
            <button class="btn btn-primary" type="submit">Submit Request</button>
        </div>
    </div>
</form>

<?php require_once 'templates/footer.php'; ?>

1
  • 1
    @BhavikKalariya no need to post such comments. Commented Jan 1, 2020 at 7:09

2 Answers 2

2

Your code is so congested so here is the demo that you want. Hope this helps you!

Just under document ready have change event on checkbox and check if the textbox have requird attribute. Just toggle it with the help of if else condition.

$(document).ready(function() {
    $('.checkbox').change(function() {
        if ($('.inputBox').attr('required')) {
           $('.inputBox').removeAttr('required');
        } 
        else {  
           $('.inputBox').attr('required','required');
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form>
<p><input type="checkbox" class="checkbox" /> Check Me to make the Text Box a Required Field</p>
<input type="text" class="inputBox" />
<input type="submit" value="Submit" />
</form>

Sign up to request clarification or add additional context in comments.

3 Comments

You should be more specific with those selectors.
You selectors are still not enough specific. Your code might not work as expected and it's error prone.
Added class @RokoC.Buljan
0

You can check when the form is submitted. Let's say, the user selects first checkbox The categories of personal information get_company(); ?> has collected about you.

let checkbox1 = document.querySelector('.checkbox1:checked').value;
if(checkbox1){
  if(!document.getElementById('checkbox1InputFiedl1').value || 
  !document.getElementById('checkbox1InputFiedl2').value){
     alert("Error: fields not filled")
  }
}

1 Comment

An empty space is also a value... and BTW checkboxes are not required to hold a value...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.