How to make the button inactive when pressing the radio button?

I want to make the submit button inactive (not clickable) until one of the form radio buttons is checked.

This is what I have so far:

{% for answer in form.poll.answers.all %}
    <p class='field radio question'>
        <input id='{{ form.answer.auto_id }}_{{ answer.pk }}' type='radio' name='{{ form.answer.html_name }}' value='{{ answer.pk }}' />
        <label for='{{ form.answer.auto_id }}_{{ answer.pk }}'>
            <em>{{ answer }}</em>
        </label>
    </p>
{% endfor %}

<button class='buttons' type='submit' id='id_vote_button'>{% trans "Vote" %}</button>

<script src='{% static 'scripts/libs/jquery.js' %}'></script>

<script>
    $("input.radio").on('click', function () {
        console.log("click test");
        if ($('form.poll input.radio:checked')[0]) {
            console.log("true test");
            $("#id_vote_button").setAttribute('active', true);
        }
        else {
            console.log("false test");
            $("#id_vote_button").setAttribute('active', false);
        }
    });
</script>

      

The problem is that it $("input.radio").on('click', function ()

has no effect in the console when I click on the radio buttons.

+3


source to share


3 answers


You need to set the property of the disabled

button that can be accessed with .prop()

and use the correct selector :radio

to orient the radio elements.

$(":radio").on('change', function () {
    $("#id_vote_button").prop('disabled', $('form.poll :radio:checked').length == 0);
});

      



I would recommend using change

event insteadclick

Note: there is no method setAttribute()

defined in jQuery

+1


source


I think you shouldn't be catching the 'click' event, but the "change" event.

$("input.radio").on('change', function () {
...
}

      



or

$("input.radio").change(function () {
    ...
}

      

0


source


I used Satpals answer but modified it slightly to use the function .is()

provided by jQuery

$("input.radio").on('change', function () {
    $("#id_vote_button").prop('disabled', $('form.poll input.radio').is(':checked'));
});

      

or you can even use $(this)

$('input.radio').on('change', function () {
    $('#id_vote_button').prop('disabled', $(this).is(':checked'));
});

      

0


source







All Articles