user5296504
user5296504

Reputation:

Make input="text" field required if checkbox was selected

i have a bootstrap formular which include two different addresses

The first address is the main address of the user and all fields are required.

The second address is the billing address and this field (street, street number, zip code and city) should be required if the user select the "billing address checkbox".

I work with http://formvalidation.io/ but i don't know how to get the dependence between checkbox and my billing address input fields.

Maybe someone can help?

Upvotes: 1

Views: 15142

Answers (2)

Marek Sapiński
Marek Sapiński

Reputation: 138

You can also check if the checkbox is actually checked rather than when it is clicked. It will work better for scenarios where you use already checked fields.

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="checkbox_name"]' ), document.querySelector( 'input[name="input_text"]' ) );

Upvotes: 3

Rounin
Rounin

Reputation: 29463

You can add a jQuery .change() event listener to the checkbox which then toggles the required attribute on the text input:

$(document).ready(function() {

    $('input[type="checkbox"]').change(function() {

        if ($('input[type="text"]').attr('required')) {
            $('input[type="text"]').removeAttr('required');
        } 

        else {
            $('input[type="text"]').attr('required','required');
        }

    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
<p><input type="checkbox" /> Check Me to make the Text Box a Required Field</p>
<input type="text" />
<input type="submit" value="Submit" />
</form>


Here is the same approach in native javascript so that you can compare and contrast against the jQuery:

var checkBox = document.querySelector('input[type="checkbox"]');
var textInput = document.querySelector('input[type="text"]');

function toggleRequired() {

    if (textInput.hasAttribute('required') !== true) {
        textInput.setAttribute('required','required');
    }

    else {
        textInput.removeAttribute('required');  
    }
}

checkBox.addEventListener('change',toggleRequired,false);
<form>
<p><input type="checkbox" />Check Me to make the Text Box a Required Field</p>
<input type="text" />
<input type="submit" value="Submit" />
</form>

Upvotes: 8

Related Questions