I need either:
Radio buttons that can be deselected OR
Mutually exclusive checkboxes
Background info:
I have a repeater.
For each row in the repeater there is an associated document that can be either "Generated" or "Reprinted".
The user should be able to select up to one checkbox in any given row. After this, one button click will handle all of their selections in one pass.
When I search for "Mutually exclusive checkboxes", the common response is, "This is what radio buttons are for."
When I search for "Deselectable radio buttons", the common response is, "This is what check boxes are for."
Others have suggested custom JavaScript/ jQuery solutions but none in which the number of CheckBoxes/RadioButtons and their IDs are variable.
I find it hard to believe that this functionality isn't supported by ASP.NET controls. Has anyone faced this problem? Is there another control I could use or does this require a custom solution?
NOTE: The only third party software I have access to is Telerik's UI for ASP.NET AJAX, which doesn't contain an obvious solution.
Sample "Mutually exclusive checkboxes" in a repeater using Javascript:
window.onload = function(){
var repeater = document.getElementById('repeater');
var chks = repeater.querySelectorAll('[type=checkbox]');
for(var i = 0,chk;chk = chks[i];++i){
chk.onclick = function(){
if(this.checked){
for(var j=0,ch;ch=chks[j;++j]){
if(ch !== this)
ch.checked = false;
}//for
}//if(this...
}//chk.onclick
}//for(var i
}//window.onload
use a checkboxlist and handle the SelectedIndexChanged
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (checkedListBox1.CheckedItems.Count > 0)
{
foreach (int i in checkedListBox1.CheckedIndices)
{
checkedListBox1.SetItemCheckState(i, CheckState.Unchecked);
}
}
}
I'm more of a StackOverflow guy, but I eventually found this on GitHub.
https://gist.github.com/kikegarcia/6104607
And here's what I ended up with, along with some documentation. Basically the same thing, but using .prop instead of .attr since reading Tim Down's explanation of the difference between the two here: .prop() vs .attr()
// mutually exclusive checkboxes within the scope of a repeater row
function cbOnClick(sender) {
if (sender.checked)
$(sender).siblings(":checkbox").prop("checked", false);
// 1 2 3 4 5 6
}
Get the event-initiating checkbox as a jQuery object.
Get the sibling elements of our checkbox...
... with type = "checkbox".
Access their properties...
... of type "checked"...
... and set them to false. => Automatic unchecking of sibling checkboxes.
Related
Here, I've three radio group in a single page. But in the entire page I want to select only one radio option. Like if I'm selecting Monday then Tuesday selection should be unchecked automatically. How can I proceed with the logic, below logic is not working as expected.
sample JSON :
{
report:[
{
day:'Monday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Tuesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Wednesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
}
]}
JS code
for(var I=0; I<reports.length; I++){
var radios = document.getElementsByTagName('input')
if(radios[I].type === 'radio' && radios[I].checked){
document.getElementById(radios[I].id).checked = false
}
If you're able to create radio buttons in SurveyJS, you should be able to give the button group a name, so there would be no need for any additional JavaScript. Check out their documentation for an example.
Looks like the sort of nested structure you have for the buttons could be achieved with something like a dynamic panel or cascading conditions in SurveyJS. You should be able to render the available time slots dynamically with "visibleIf" based on the selected day.
I would definitely dig around the documentation of SurveyJS to find a solution there rather than hacking your way around it. But solely as an exercise, the problem in your current code could be that you're selecting a button by ID, which will not work correctly if you have tried to give the same ID to multiple buttons. After all, you already have the target button as radios[I], so you could just use radios[I].checked = false. Or the issue could be that you're unchecking the selected button AFTER the new selection has been made, which might actually uncheck the button you just clicked. Hard to say without additional information, but in any case, looping your inputs based on a value that might be something else than the actual number of inputs (you're using reports.length) is probably not the best idea, since that value might be different from the number of inputs in your form, which would mean that not all of them are included in the loop. Here are a couple of examples of what you could do instead:
// Get all radio buttons
const radioButtons = document.querySelectorAll('input[type="radio"]')
// If you need to uncheck the previously selected one (don't do this if you can avoid it!)
radioButtons.forEach(radioButton => {
// Use a mousedown event instead of click
// This gives you time to uncheck the previous one before the new one gets checked
radioButton.addEventListener('mousedown', () => {
// Get the currently selected button and uncheck it
const currentlySelected = document.querySelector('input[type="radio"]:checked')
if (currentlySelected) currentlySelected.checked = false
})
})
// You can add further options to the querySelector, such as [name]
// This gets the currently selected button in the specified group
const checkedRadioButton = document.querySelector('input[type="radio"][name="group-name"]:checked')
Here's a fiddle demonstrating this sort of "fake" radio button functionality (without a "name" attribute).
You can give all these radio buttons the same name, then one radio only will be checked.
I have something in my mind, but I have no idea how to get it done, so I hope I can get some advise here.
I'm working on an activity registration app (using Laravel), where every activity will be registered. Very important is that we need to record who was invited and who actually attended. I already have this part running. My issue is more on the practical side.
I use jQuery Select2 for the multiple select fields for invitees and attendees. Imagine now that there's a group of users that need to be invited or attend virtually all activities, while the invitation or attendance of others depends on the type of activity. Using Select2, I can only select users one at a time and that sucks if you need to do that for, say, 50 users for virtually every activity.
What is the best way to have a "group" that can be selected, which selection fills in all the names of those in the group in the select field? Or is there a better way to get this done?
I'm seeing something in my head, where there are checkboxes next to the select field, representing the groups. When you tick a checkbox of a group, the select field is populated with all users who are part of that group.
I have no idea ow this can be done. I looked around and every search brings up select boxes populating select boxes. None handle checkboxes.
Any advise on how to get this done?
My PHP/MySql is intermediate, Javascript/Ajax is very basic.
One strategy would be to build a control (checkbox element) that will set or toggle the selection of your group of users whenever it's clicked. Say we have the following markup:
<select class="my-big-group-select" multiple="multiple">
<!-- assorted options here -->
</select>
<label>
<input type="checkbox" class="toggle-default-group" />
Use my default big group of users
</label>
The Select2 API allows you programmatic control over the component it generates.
You can read more about it here: https://select2.github.io/examples.html#programmatic
Here's one way to leverage this knowledge using jQuery with Select2:
<script>
var groupSelect = $('.my-big-group-select').select2();
var groupToggle = $('.toggle-default-group');
var myBigGroup = ["Aaron", "Beth", "Cindy"]; // assorted option values
groupToggle.on("click", function() {
if ($(this).is(':checked')) {
groupSelect.val(myBigGroup).trigger('change');
} else {
var currentlySelected = groupSelect.val();
if (currentlySelected) {
var filteredSelections = currentlySelected.filter(function(key) {
return myBigGroup.indexOf(key) < 0;
});
groupSelect.val(filteredSelections).trigger('change');
}
}
});
</script>
Here's a CodePen that shows it all in action: http://codepen.io/anon/pen/qNQKOd
Of course you can build on this to make additional enhancements (the ability to select multiple groups, for example).
As an alternative, you may consider other code libraries like Bootstrap Multiselect: https://davidstutz.github.io/bootstrap-multiselect/
Hope this points you in the right direction!
I have 7 drop down boxes with "YES" and "NO" answers. They are all on the same page. Along the side of the page, as the user selects yes or no for each answer, I want to have a count that shows how many times they have selected no, and how many times they have selected yes, to update as they fill out the form. So Yes=1, NO= 4, etc. As they select another yes, one is added. If they change their answer to "no", a "yes" is deleted and a "no" is added to the count.
I am assuming this will be javascript? I am running an asp site so php wont work in this case.
This is used as a reference BEFORE they submit the form, so queries to find out after they submit are useless here.
Yes the solution is easy in JavaScript with jQuery, you supose all the answers by default are yes and start the counter of yesCounts = 7 and if someone is clicking no you decrement yesCount-- and increment noCount++
var yesCount = 7;
var noCount = 0;
$(".no-element").on('click', function () {
noCount++;
yesCount--;
});
$(".yes-element").on('click', function () {
yesCount++;
noCount--;
});
So you should add the class <options class='yes-element'>Yes</options> and <options class='no-element'>No</options> and make all the default values in options yes
You can do this in many ways, one can be javascript and jquery.
$("#dropDownId").val();
jquery's doc
I have created this little jsbin, with the framework for my use case: http://emberjs.jsbin.com/kufijixicu/1/edit?html,js,output
What I have tried to achieve in various ways, is to be able to assign the color value based on the selection in the list of radio buttons. I believe there to be a simple solution to this.
The solution must also provide a way where a potential existing value is already selected in the list. So if color is already selected, the selected one should be checked in the list.
Current solution
My current solution may be irrelevant, but I'll post it here for context.
As mentioned, I've tried various solutions. The one I have in my application at this moment works as described, it's buggy and messy which is why I'm looking for a better solution:
The ColorController has an action, which is attached to what would be the <li> in above jsbin:
selectColor: function(color) {
this.send('setColor', color);
this.forEach(function(item) {
item.set('isChecked', item.get('model') == color);
});
}
The IndexController has the setColor action:
setColor: function(color) {
this.set('color', color);
}
And the initial selection is set through this observer on the ColorController:
colorsChanged: function() {
if (this.filterBy('isChecked', true).get('length') == 0) {
var selectedColorId = this.parentController.get('model.color_id')+'',
selectedColor = this.filterBy('id', selectedColorId);
if (selectedColor.get('length') == 0) return;
selectedColor.objectAt(0).set('isChecked', true);
}
}.observes('this.[]')
This seems way too messy, but it also doesn't work 100%. For instance, a click on the radio button itself will actually un-check the radio button again.
In Ember, things like radio buttons and checkboxes are best wrapped up in components. Unfortunately, a few edge cases have prevented Ember from shipping a radio button component as part of core.
The first thing I'd do is see if someone else has already implemented this. Are you using Ember CLI? If not, you should be. Browsing Ember Addons I find two radio button components.
I'd give ember-radio-button a shot.
I'm using the jQuery validation plugin and I'm looking to add some custom logic. I have a series of checkboxes which have children checkboxes associated with them. For certain (not all) of these parent checkboxes, I want to require that one of the children checkboxes is checked. I have no issue hardcoding for this so I was adding a field like this to my DOM:
<input type="hidden" id="child_required_1" class="child_required_1" />
And then adding a custom validator like this:
jQuery.validator.addMethod('child_required_1', function(val, element) {
if($('#product_responses_1').length > 0) {
if($('#product_responses_1').is(':checked')) {
var count = $("input:checkbox:checked[id^='children_tags_1_']").length;
if(count == 0) {
return false;
}
}
}
return true;
}, 'You must select at least one child.');
This works perfectly fine. But when I duplicate all of this and add "_2", only one of the validators seems to fire. So from what I can gather, custom validators are unique per form? If that's the case, how am I supposed to handle a situation like this where I may need 15-20 of these all showing in different places? I don't want to just show one error.
I could also create a class rule but that doesn't solve my problem of creating multiple error labels and placing them in the relevant positions.
Apparently having it on a hidden field didn't work, but when I removed the hidden fields and applied that class to the actual checkboxes themselves, it worked fine. Not entirely sure why.