Radio button validation in javascript for multiple screens - javascript

I am looking for some help on how to validate radio buttons generically across multiple screens and make the script reusable. I have manage to get it working by using a single class $('.radio_validate'). However, if I want to reuse the script for any other pages I would have to duplicate the script which is not ideal.(I'm not super familiar with JS so appreciate any support on this.)
Here's the code specifically on the radio button validation. Basically adding the error class if not checked and remove the error class if checked. Ideally, I would like to make $('.radio_validate') into something that is reusable if possible.
if( $('.radio_validate').is(':visible') && !$('.radio_validate').is(':checked') ){
$('.radio_validate')
.closest('.form__item')
.addClass('error');
shakeCurrentCard( $('.radio_validate').closest('.step') );
//return false;
}
else {
$('.radio_validate')
.closest('.form__item')
.removeClass('error');
}

If you plan on having every single radio button validated no matter the page, then use:
$("input[type='radio']")
However, if you don't want all of the radio buttons to be validated, then adding a class or data-attribute, to the radios you want validated is the best option.
loops through the radio instead of doing them all at once:
$("input[type='radio']").each(function() {
if ($(this).is(':visible') && !$(this).is(':checked')) {
$(this)
.closest('.form__item')
.addClass('error');
shakeCurrentCard($(this).closest('.step'));
//return false;
} else {
$(this)
.closest('.form__item')
.removeClass('error');
}
});

Related

Do I need to refactor this javascript for conditional form logic?

I have a form in Laravel that goes over several template (blades). For each template I am implementing simple conditional logic to show and hide groups of questions.
For the templates, I'm using HTML5 for efficient client-side validation. I wrote the javascript below to show and hide fields using HTML attributes.
The example below responds to a yes/no question by exposing hidden sets of radio buttons. One set is for answering Yes, one is for No.
My question is, do I need to refactor this? Is there a more efficient way I should be writing this javascript, or am I doing ok?
I'm using an event listener so that clicks can bubble up, understanding that this is most efficient. Since I have more than one page, I have more than one event listener, one for each template. Is there a better way to do that?
Thanks for your input.
// "Purpose of Notification" Blade
document.addEventListener('click', function (event) {
// When yes or no is choosen
if (event.target.matches('#waiver30100byes')) {
// show the patient level group container
document.getElementById("patient-level").removeAttribute("hidden");
// and show 100 level for yes and make it required
document.getElementById("patient-level-100").removeAttribute("hidden");
document.getElementById("level1").required = true;
// hide and un-require the 30 level radio group
document.getElementById("patient-level-30").hidden = true;
document.getElementById("level3").required = false;
}
else if (event.target.matches('#waiver30100bno')) {
// show the patient level group
document.getElementById("patient-level").removeAttribute("hidden");
// and show 30 level for no and make it required
document.getElementById("patient-level-30").removeAttribute("hidden");
document.getElementById("level3").required = true;
//hide and un-required the 100 level radio group
document.getElementById("patient-level-100").hidden = true;
document.getElementById("level1").required = false;
//
}
}, false);

check box validation javascript

I need to validate the selection of at least one check box on a table. I am not using an alert because I already have a class on CSS that highlights in red the inputs, selects and other elements if they are not filled out.
This is my JS:
var btnRegister= document.querySelector('#btnRegisterRegObr');
btnRegister.addEventListener('click', function () {
var bError= false;
//I am initializing this boolean variable so that it also shows an error
//message on the screen if the user has not selected any option at all...
var elementCheckRegObr = document.querySelector('#checkRegObr');
if (elementCheckRegObr.checked==false){
bError=true;
elementCheckRegObr.classList.add('error');
//This part of the code brings the error I have
//previously created on CSs if the checkbox is not checked
}
else{
elementCheckRegObr.classList.remove('error');
}
});
The button on HTML has the right id on the HTML: id="btnRegisterRegObr.
I was looking at some codes here and people were validating using the .checked==false
However this does not seem to work for mine.
As a matter of fact, I first thought I needed to use the syntax of if (elementCheckRegObr.checked=="") but that one does not seem to work either.
I dont have problems validating inputs, selects nor radio buttons, but I am not sure if I am doing it on the right way with the check boxes. Any help or advice would be greatly apprecciate it :)
I suggest that you use getElementById to get your elements, and test if the checkbox is checked this way:
if(document.getElementById('idOfTheCheckBox').checked){
alert('hey, im checked!');
}

Best way to assign value from radio button selection

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.

jQuery Custom Validators

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.

Javascript tickbox validation

I am trying to add javascript validation to a bunch of check boxes, basically what I want is as soon as the user has selected 3 tickboxes, it should disable all of the tickboxes except the three that were ticked.
How could I go about doing that?
Thanx in advance!
The following will disable the rest of the checkboxes if you select 3 of them, and also enable them once you uncheck one of the three selected..
$(':checkbox').click(
function(){
var selected = $(':checkbox:checked').length;
if (selected == 3)
{
$(':checkbox:not(:checked)').attr('disabled',true);
}
else
{
$(':checkbox:not(:checked)').attr('disabled',false);
}
}
);
Live demo
Have on onclick handler that when a checkbox is clicked it ups a counter by one if it is unchecked it decreases the count. After raising the count, test to see if it is three. Then probably the easiest method is to either save the ids of the three checked boxes or save them in the previous step. Then change the click event to return true only if the ids match the saved ids.
Sorry I don't have time right now to actually write up any code. Hopefully this will get you started.
jQuery
$("#container :checkbox").click(function(){
if ($("#container :checkbox").length >= 3) {
$("#container :checkbox").attr("disabled", "disabled");
}
});

Categories

Resources