Search code examples
javascriptrequired

Add required attribute when radio is checked


I have a set of radiobuttons called 'price'. When the '€' radio button is selected, I want to focus on a text input field and that text input field should be required. When I click another option, the requried attribute should be removed.

Is this possible through Javascript or jQuery? I found a jQuery snippet here, but it doesn't seem to be working. This is what I have now:

<input type="radio" name="price" value="value" id="value_radio" onclick="document.getElementById('value_input').focus()" required>

<label for="value_input">&euro;</label>
<input type="text" name="price_value" id="value_input" pattern="\d+(,\d{1,2})?" 
    onclick="document.getElementById('value_radio').checked=true">

<script>
    $('#value_radio').change(function () {
        if($(this).is(':checked')) {
            $('#value_input').attr('required');
        } else {
            $('#value_input').removeAttr('required');
        }
    });
</script>

<input type="radio" name="price" id="free" value="free">
<label for="free">Free</label>

JSFiddle: http://jsfiddle.net/fhfrzn1d/


Solution

  • According to this answer, you have to monitor the change on both radio inputs. So move your javascript script after the second radio.

    Also there was missing a )

    Fiddle updated: http://jsfiddle.net/fhfrzn1d/1/

    $('input[name="price"]').change(function () {
        if($("#value_radio").is(':checked')) {
            $('#value_input').attr('required', true);
        } else {
            $('#value_input').removeAttr('required');
        }
    });