Add required attribute when radio is checked

安稳与你 提交于 2019-12-13 02:37:03

问题


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/


回答1:


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');
    }
});



回答2:


You have two (really three) mistakes in your code.

First. The syntax is invalid. You should fix the closing brace as @Hushme recommends in the comments.

First (2). Your usage of jsfiddle is invalid too. You should paste the code to the JavaScript section of the site and also enable jQuery library.

Second. $('#value_input').attr('required') is not creating an attribute; it's a getter. You should use the proper setter there:

$('#value_input').attr('required', true);

Third. The radiobutton change event is not firing when user deselects the radiobutton. So you should handle events on all the buttons:

$('input[name="price"]').change(function () { ... });

I've fixed your jsfiddle, see http://jsfiddle.net/fhfrzn1d/4/



来源:https://stackoverflow.com/questions/25340186/add-required-attribute-when-radio-is-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!