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.
source to share
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
source to share
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'));
});
source to share