Javascript Validation of both Checkboxes and Radio Buttons - javascript

I am doing a checklist that needs to be completed each time a member of staff completes this particular form. Please note that I am still grasping JS slowly due to not having a large amount of time to research.
I have done a bit of research and combined some different validation styles and come up with this;
function validate(form) {
var e = form.elements;
if(e['reloaded'].value == "yes") {
if(!e['Q1-A'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['Q1-B'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['Q1-C'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['Q1-D'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['Q1-E'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['Q1-G'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['Gen-A'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['Gen-B'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['invoice_number'].value) {
alert('Invoice Number is REQUIRED!');
return false;
}
return true;
} else if(e['reloaded'].value == "no") {
if(!e['Gen-A'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['Gen-B'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['Q2-A'].value) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['invoice_number'].value) {
alert('Invoice Number is REQUIRED!');
return false;
}
return true;
} else if(!e['reloaded'].value) {
alert('You must indicate if you Reloaded the OS!');
return false;
}
}
At this stage it is simply returning "You must indicate if you Reloaded the OS!" even when it is selected.
The point is to select an option from a radiobutton selection, then it will show some checkboxes and all checkboxes must be checked before the form can be submitted. Obviously some checkboxes only show if a particular option is selected and as such some need to be excluded from being required.
There is also an additional field that needs to be filled (invoice_number) which has always had validation on it and has always worked.
The Radio Buttons:
<input name="reloaded" id="reloaded" type="radio" value="yes" onClick="Q1(this.value);" /> Yes</label> <label><input name="reloaded" id="reloaded" type="radio" value="no" onClick="Q1(this.value);" />
The Checkboxes are all the same except the ID's/Names
<input name="Q1-A" id="Q1-A" type="checkbox" value="yes" />
Required Text Box:
<input class="field size5" type="text" name="invoice_number" id="invoice_number" placeholder="Required! - 'RA' for Warranty Jobs" />
I am sure that I have over complicated it due to my lack of knowledge, however I just cannot think of where i have gone wrong.
(Submission is occurring via onsubmit="return validate(this);")

The following code was my final result and it works;
function validate(form) {
var e = form.elements;
if(document.getElementById('RL-Y').checked) {
if(!e['Q1-A'].checked || !e['Q1-B'].checked || !e['Q1-C'].checked || !e['Q1-D'].checked || !e['Q1-E'].checked || !e['Q1-G'].checked || !e['Gen-A'].checked || !e['Gen-B'].checked) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['invoice_number'].value) {
alert('Invoice Number is REQUIRED!');
return false;
}
return true;
} else if(document.getElementById('RL-N').checked) {
if(!e['Gen-A'].checked || !e['Gen-B'].checked || !e['Q2-A'].checked) {
alert('You Must complete the Checklist!');
return false;
}
if(!e['invoice_number'].value) {
alert('Invoice Number is REQUIRED!');
return false;
}
return true;
} else {
alert('You must indicate if you Reloaded the OS!');
return false;
}
}

Related

jquery return false killed submit event?

I try to use loop to validate each of every input whether they are filled or not. But end up my submit_form function doesn't get triggered.
$('#submit').click(function(){
var hold = true;
if ($('.tab2').hasClass('active') && hold == true) {
$('.tab-content:visible input').each(function(i, val) {
if ($(this).val() == '') {
alert("Please fill in valid " + $(this).attr('data-error'));
$(this).focus();
hold = true;
return false;
} else {
hold = false;
}
});
return false; //can't remove this
}
submit_form(); //not triggered although all inputs are filled
})
if I removed the return false, there will be no checking..

Can't return form submit to false

So I have a form, and if the input is invalid, I won't let the form pass like so
$(".main-form").submit(function(e){
return false;
});
This won't let the form pass. When the user complete everything correctly I try to do this
$(".main-form").submit(function(e){
return true;
});
But for some reason it stays false all the way though. Any workarounds?
You should use a single submit handler:
$(".main-form").submit() {
if (...) {
return true;
} else {
return false;
}
}
where ... contains your validation checks. The actual code might be somewhat more complex, e.g.
if (field1 is invalid) {
return false;
} else if (field2 is invalid) {
return false;
}
...
} else {
return true;
}
You have to clear the old handler, so you'd initialize it like this:
$(".main-form").on('submit', function(e){
return false;
});
Then to change the handler:
$(".main-form").off('submit');
$(".main-form").on('submit', function(e){
return true;
});

RegEx not working with my jQuery

Can someone help me please, I want to show an error when the user makes an invalid input with jquery.
It works if the input is null, but does not work with RegEx.
Here is the html code :
<div class="error" style="padding:5px 10px;background-color:yellow;border:1px solid red;border-radius:5px;display:none"></div>
<input type="text" name="nama">
<input type="submit" name="submit" value="Cek">
And here the jQuery
$(document).ready(function () {
var justChar = /^[a-zA-Z]+$/;
$('input[name="submit"]').click(function () {
if ($('input[name="nama"]').val() === "") {
$('.error').html('<ol></ol>');
if ($('input[name="nama"]').val() === "") {
$('.error ol').append("<li>Name Must Be Require</li>");
} else if (!justChar.test($('input[name="nama"]').val())) {
$('.error ol').append("<li>Name Must Be Character</li>");
}
$('.error').slideDown('slow');
return false;
}
return true;
});
});
i've write in jsfiddle
Remove the parent condition if ($('input[name="nama"]').val() === "") as it is nonsense if you want to analyse your input value.
And for matching the regex, use the jQuery style method: $('input[name="nama"]').val().match(justChar);
Your regex check is misplaced, it is under the condition if ($('input[name="nama"]').val() === "") So the regex will never be checked
I got this working:
$(document).ready(function(){
var justChar = /^[a-zA-Z]+$/;
$('input[name="submit"]').click(function(){
if($('input[name="nama"]').val() === "") {
$('.error').html('<ol></ol>');
$('.error ol').append("<li>Name Must Be Require</li>");
$('.error').slideDown('slow');
return false;
} else if(!justChar.test($('input[name="nama"]').val())) {
$('.error').html('<ol></ol>');
$('.error ol').append("<li>Name Must Be Character</li>");
$('.error').slideDown('slow');
return false;
} else {
return true;
}
});
});
Your inner condition is checked only if the value is empty.
If it is not empty then your inner condition check is not even made. see outer check -
if ($('input[name="nama"]').val() === "") {
update: Also, better to use the JQuery match as #Valentin Mercier has suggested. That's a good one
Remove the above line and your errors show up properly
Edit:
Showing the modified code for more clarity to the OP
$(document).ready(function () {
var justChar = /^[a-zA-Z]+$/;
$('input[name="submit"]').click(function () {
if ($('input[name="nama"]').val() === "") {
$('.error').html('<ol></ol>');
$('.error ol').append("<li>Name Must Be Require</li>");
$('.error').slideDown('slow');
return false;
} else if (!$('input[name="nama"]').val().match(justChar)) {
$('.error').html('<ol></ol>');
$('.error ol').append("<li>Name Must Be Character</li>");
$('.error').slideDown('slow');
return false;
} else {
$('.error').hide();
return true;
}
});
});
Edit: Sharing the jsfiddle as the OP has still no idea! . Hope it helps!
http://jsfiddle.net/PrasanthSudarsanan/tLmD7/2/

Form refresh after .submit() event

I am validating a form that's working fine but i don't know why the form not submit after all validations.
Here is validation code:
$('#coupon_options').submit(function(e){
e.preventDefault();
var name = $('input[name="coupon_name"]'),
code = $('input[name="coupon_code"]'),
value = $('input[name="coupon_value"]'),
valid = $('input[name="coupon_valid"]'),
status = true;
if( $.trim(name.val()) == "" ){
name.css('border-color', '#ff0000');
status = false;
} else { name.removeAttr('style'); }
if( $.trim(code.val()) == "" ){
code.css('border-color', '#ff0000');
status = false;
} else { code.removeAttr('style'); }
if( $.trim(value.val()) == "" ){
value.css('border-color', '#ff0000');
status = false;
} else { value.removeAttr('style'); }
if( $.trim(valid.val()) == "" ){
valid.css('border-color', '#ff0000');
status = false;
} else { valid.removeAttr('style'); }
if( status == true ){ return status; }
else { return false; }
});
As i know to stop the refresh after submit event i have used the return false but i am not sure return true works here or not?
I don't want to use Ajax, just want to submit after validation.
Is there something wrong in this code??
remove:
e.preventDefault();
it stopping the default action to occur even you return true;.
For example:
Prevent a submit button from submitting a form
Prevent a link from following the URL
e.preventDefault(); is the issue, but you should note that it's never a good sign when you have multiple functions that basically perform the same action for different elements, you can simplify your code to this:
$('#coupon_options').submit(function(e){
var status = true;
$('input[name="coupon_name"],input[name="coupon_code"],input[name="coupon_value"],input[name="coupon_valid"]').each(function(){
if($.trim($(this).val()) == ""){
$(this).css('border-color', '#ff0000');
status = false;
} else {
$(this).removeAttr('style');
}
});
return status;
});
And you could even use $('input[name^="coupon_"]') to select all inputs that start with that prefix.

using getElementsByName to validate radio button

I'm attempting to validate whether a group of radio buttons is checked in order o validate a form.
function formValidator() {
var triedIt = document.getElementsByName('tried');
if(radioChecked(triedIt, "Please select") {
return true;
}
return false;
}
function radioChecked(elem, helperMsg) {
if(document.myform.tried.checked == 1) {
return true;
}
else {
alert(helperMsg);
elem.focus();
return false;
}
}
This returns the alert, but for some reason the form gets processed anyway. I'm wondering what I'm doing wrong... any help would be appreciated.
If you're wondering why I don't just use jquery etc... its unfortunately not an option. Thanks!
I think it's happening because document.getElementsByName('tried') returns array of elements. So, when you call elem.focus() it will throw error (because array haven't method focus) and js stops execution.
function formValidator(){
var triedIt = document.getElementsByName('tried');
if(radioChecked(triedIt, "Please select")){
return true;
}
return false;
}
function radioChecked(elem, helperMsg){
if(document.myform.tried.checked == 1) {
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
try this i think you skipped one closing bracket ) in if(radioChecked(triedIt, "Please select")) that`s why its happening

Categories