Suavocado
Suavocado

Reputation: 969

Rails/JQuery: Hide submit button unless at least 1 checkbox is selected

I want to hide the submit in a form button unless at least one of the checkboxes is selected. Here is a sample of my view

<div class="ck-button">
    <label class="checklabel">
        <%= f.check_box :swim , class:"activityCK" %><span>swim</span>
    </label>
</div>
<div class="ck-button">
    <label class="checklabel">
        <%= f.check_box :spin , class:"activityCK" %><span>spin</span>
    </label>
</div>
<div class="ck-button">
    <label class="checklabel">
        <%= f.check_box :climb , class:"activityCK" %><span>climb</span>
    </label>
</div>

<%= f.submit 'SPOT ME!', class:"btn btn-danger bt-lg submit" %>

I found this code from another user (I already confirmed that it loads correctly)

var checkboxes = $("input[type='checkbox']"),
    submitButt = $("input[type='submit']");

checkboxes.click(function() {
    submitButt.attr("disabled", !checkboxes.is(":checked"));
});

but it doesn't seem to have an effect.

Any help appreciated

Upvotes: 2

Views: 1204

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240858

Listen to change event of the checkboxes rather than the click event, and then combine the :checked pseudo-class with the .length property in order to determine if there are any checked checkboxes.

Example Here

$(':checkbox').on('change', function () {
    $('input[type="submit"]').prop('disabled', !$(':checkbox:checked').length);
}).change();

$(':checkbox').on('change', function () {
    $('input[type="submit"]').prop('disabled', !$(':checkbox:checked').length);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ck-button">
    <label class="checklabel">
        <input type="checkbox"><span>swim</span>
    </label>
</div>
<div class="ck-button">
    <label class="checklabel">
        <input type="checkbox"><span>spin</span>
    </label>
</div>
<div class="ck-button">
    <label class="checklabel">
        <input type="checkbox"><span>climb</span>
    </label>
</div>

<input type="submit" value='SPOT ME!' class="btn btn-danger bt-lg submit" />

Upvotes: 4

Chris Tate
Chris Tate

Reputation: 458

Try using prop() instead of attr().

Upvotes: 1

Related Questions