Reputation: 155
I have the following:
HTML:
<input type="checkbox" name="1" value="" id="1" onclick="enableNextButton('5')">
<input type="checkbox" name="2" value="" id="2" onclick="enableNextButton('5')">
<input type="checkbox" name="3" value="" id="3" onclick="enableNextButton('5')">
<button type="button" id="next-btn-5" disabled>Submit</button>
Javascript:
function enableNextButton(quizID) {
if($("input[type=checkbox]").prop('checked') == true){
$('#next-btn-'+quizID).prop('disabled', false);
}else{
$('#next-btn-'+quizID).prop('disabled', true);
}
}
The problem is that it is only working for the first checkbox, for others it does not work, it does not fulfill the function.
Upvotes: 1
Views: 422
Reputation: 206638
I would use the data-* attribute to store the button selector (ID in your case):
$("[data-enable]").on("input", function() {
const selector = this.dataset.enable
const $group = $(`[data-enable="${selector}"]`);
let ok = false;
if (/checkbox|radio/.test(this.type)) ok = $group.filter(":checked").length > 0;
if (/textarea/.test(this.type)) ok = $(this).val().trim().length > 0;
$(selector).attr("disabled", !ok);
});
<input type="checkbox" name="5-1" value="1" data-enable="#next-btn-5">
<input type="checkbox" name="5-2" value="2" data-enable="#next-btn-5">
<input type="checkbox" name="5-3" value="3" data-enable="#next-btn-5">
<button type="button" id="next-btn-5" disabled>Submit 5</button>
<br>
<input type="radio" name="30" value="1" data-enable="#next-btn-30">
<input type="radio" name="30" value="2" data-enable="#next-btn-30">
<input type="radio" name="30" value="3" data-enable="#next-btn-30">
<button type="button" id="next-btn-30" disabled>Submit 30</button>
<br>
<textarea name="foo" data-enable="#next-btn-31"></textarea>
<button type="button" id="next-btn-31" disabled>Submit 31</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 171700
Since you are using jQuery it is simpler to create a jQuery event listener than use an inline onclick
and use a data attribute for the nextId value
$(':checkbox[data-next]').change(function(){
$('#next-btn-' + $(this).data('next')).prop('disabled', !this.checked);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>5:<input type="checkbox" name="1" value="" id="1" data-next="5"/></label>
<label>6:<input type="checkbox" name="2" value="" id="2" data-next="6"/></label>
<label>7:<input type="checkbox" name="3" value="" id="3" data-next="7"/></label>
<br/><br/>
<button type="button" id="next-btn-5" disabled>Button 5</button>
<button type="button" id="next-btn-6" disabled>Button 6</button>
<button type="button" id="next-btn-7" disabled>Button 7</button>
Upvotes: 1