Lokman Hakim
Lokman Hakim

Reputation: 65

how to set input text automatically require when the certain radio button i checked

how to make input text required when im checked option1 radio button did i need to set value for each radio button and when im checked option2 the input text will not required

     <input type="radio"  name="ladder" value="ans1">
     <label for="option1">Option1</label><br>

     <input type="radio"  name="ladder" value="ans2">
     <label for="option2">Option2</label><br>

     <input type="text" name="ladder-meters" id="ladder-meters">

below is the javascript coding

 <script>
    $('input[name="ladder"]').change(function () {
        if($(this).is(':checked')) {
            $('#ladder-meters').attr('required');
        } else {
            $('#ladder-meters').removeAttr('required');
        }
    });
<script>

those coding basically not mine . im take it from other ppl in stackoveflow but they using this code successfully but when im try it doesnt work

Upvotes: 1

Views: 61

Answers (1)

parrker9
parrker9

Reputation: 958

When you use jQuery and attributes that only have two values (on and off), you should use the prop() function. In your case it will be:

if ($(this).is(':checked')) {
    $('#ladder-meters').prop('required', true);
} else {
    $('#ladder-meters').prop('required', false);
}

Or, if you want to save a couple of lines:

var required = $(this).is(':checked');

$('#ladder-meters').prop('required', required);

EDIT:

In your case, there is also a problem with your if condition. You should check for current value of your radio button element, like so:

$('[name=ladder]').change(function() {
    var required = ($(this).val() === 'ans1');

    $('#ladder-meters').prop('required', required);
});

See this example on this CodePen.

Upvotes: 2

Related Questions