问题
So, i have this problem with some checkboxes. First of all let me tell you about the "project" itself. It's a webform, the user must complete it and check some checkboxes and radio buttons depending on what he would like to purchase. First of them are 2 radio bullets, numbered 1 and 2, and represent the quantity of the product he wants to purchase. Next to those are about 5 checkboxes that represent the color of the product, it doesn't matter how many of them are, the thing is ... i want, when a user selects 1 at the radio buttons, only 1 checkbox to be active, if he selects 2 then only 2 checkboxes to be available to check. So.. could someone help me? I thought of jQuery but i don't know...
There are two divs, the first div with the id of let's say #radioButtons has 2 radio buttons, and the second div has the rest of the checkboxes.
回答1:
You don't give any markup in your post so I guess something like that:
HTML
<div id="radioButtons">
<input type="radio" name="quantity" id="radio1">
<input type="radio" name="quantity" id="radio2">
</div>
<div class="checkBoxes">
Color 1:<input type="checkbox" name="color" disabled="disabled">
Color 2:<input type="checkbox" name="color" disabled="disabled">
Color 3:<input type="checkbox" name="color" disabled="disabled">
Color 4:<input type="checkbox" name="color" disabled="disabled">
Color 5:<input type="checkbox" name="color" disabled="disabled">
</div>
jQuery
$('#radio1').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0)').prop('disabled', false);
});
$('#radio2').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1)').prop('disabled', false);
});
Sample workout
回答2:
We might use the real HTML source, where the problem appears.
EDIT:
I am having trouble understanding why you want to do this. From a usability point of view, this solution is quite unusual, maybe a bit bad. Let me ask you a few questions.
- Why do you want it to work like this?
- What do you want to let your users chose?
There are lots of inline selection possibilities, famous example would be chosing the iPad type on apple.com. But the most important would be to provide your users with user interfaces which are very easy to understand and a great feeling to use.
回答3:
You could add a click event to the checkboxs and then within the event handler check the conditions of max checkboxes allowed and then return true or false based on whether that limit has been reached.
回答4:
Please see the Sample
I am maintaining the number of check boxes to be created in the id of the radio and dynamically create the check boxes in the div.
EDIT:
I update the fiddle that you gave. Please take a look Update Fiddle
来源:https://stackoverflow.com/questions/10865687/limit-checkboxes-with-jquery-based-on-checked-radio-buttons