-1
Hello, I am running the following code that allows you to check a checkbox, the other options of that group are not checked. The problem is that this code allows none of the group options to be checked, but I need the user to select at least one of the "checkbox":
// the selector will match all input controls of type :checkbox
// and attach a click event handler
$("input:checkbox").on('click', function() {
// in the handler, 'this' refers to the box clicked on
var $box = $(this);
if ($box.is(":checked")) {
// the name of the box is retrieved using the .attr() method
// as it is assumed and expected to be immutable
var group = "input:checkbox[name='" + $box.attr("name") + "']";
// the checked state of the group/box on the other hand will change
// and the current value is retrieved using .prop() method
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
<div>
<h3>Fruits</h3>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Kiwi</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Jackfruit</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Mango</label>
</div>
<div>
<h3>Animals</h3>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Tiger</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Sloth</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Cheetah</label>
</div>
You want to do this when making the requisition?
– Taffarel Xavier
I want to do at the time the user selects the checkbox. The user has to select one and only one option from the group. You cannot have more than one, nor leave without "ticking" any group options.
– Renan
But you’re not already? I tested here, so when the document is loaded, none of the options is checked, so if the user clicks, from that moment on, only one option is allowed in each group.
– Taffarel Xavier
You’re right, @Taffarelxavier! In fact, what I needed was that, at this first moment (when nothing is marked), I could validate so that the user would choose at least one option. But then it is only "force" one of the options with the attribute checked in the input tag and then, if it is not the user’s option, it will change... Hehe, thanks!
– Renan
How do I mark this question as "solved"? Or do I not need to do this?
– Renan
@Renan answers the question yourself, and marks the use of the answer itself as the right one...
– Charles Fay
okay, thank you!!!
– Renan