Adding an if statement inside if statement - javascript

I have a function for a button which submits a form. This function checks to see if the 5 checkboxes are selected #co1,#co2,#co3,#div1,#cc1.
It then also checks to see if tcaccept select is set to 1.
If so the form submits, else the alert pops up.
This is the code i have at the moment:
$('#submit2pd').click(function(event) {
var $finishBoxes = $('#co1,#co2,#co3,#div1,#cc1');
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' )) {
alert('Please complete the Induction Checklist confirming that you have read and understood the Colleges main policies and procedures, agreeing to comply with these in line with the terms of your contract with the College');
return false;
}
// otherwise the form is submitted
window.location.href = "submit2pd.php";
});
All works brilliantly, but i want to add to this line as i have another option that is required. But this needs to be an if statement.
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' && THE IF STATEMENT))
this is what i need to incorporate into the if statement above.
if ($("#ctl").val() == "1") {
$('#ctlapp') must not be blank
}
else if ($("#ctl").val() == "0") {
$('#ctlapp') can be blank
}
Any help would be greatly appreciated.

How about:
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length &&
$('#tcaccept').val() == '1' &&
!($("#ctl").val() == "1" && $('#ctlapp').val() === "")))
What we're adding here is another condition which says, "And make sure it's not the case that #ctl is 1, and #ctlapp is blank".
Edit: and please see my comment above - your question is not about jQuery, forms, or validation. It's barely about JS.

if($('#tcaccept').val() == '1' && validate()) {
// do something
}
var validate = function(){
if ($("#ctl").val() == "1") {
$('#ctlapp') must not be blank
return false;
}
else if ($("#ctl").val() == "0") {
$('#ctlapp') can be blank;
return true;
}
return true;
}

I'd say clean up the code a little, and things will get a bit simpler:
$('#submit2pd').click(function(event) {
var fail_message = 'Please complete the Induction Checklist confirming that you have read and understood the Colleges main policies and procedures, agreeing to comply with these in line with the terms of your contract with the College',
$finishBoxes = $('#co1,#co2,#co3,#div1,#cc1'),
$checkedBoxes = $finishBoxes.filter(':checked'),
tcaccept = $('#tcaccept').val(),
ctl = $("#ctl").val(),
ctlapp = $('#ctlapp').val();
if (tcaccept == '1' && $finishBoxes.length != $checkedBoxes.length ) {
alert( fail_message );
return false;
} else if( ctl == "1" && ctlapp == "" ) {
alert( "some other message" );
return false;
}
// otherwise the form is submitted
window.location.href = "submit2pd.php";
});
I left the test for $('#ctl').val() == "0" out because it sounds like that's the only other value it can have, and there's no validation that needs to take place if it is "0".

Use a logic or || to capture both constalations:
$("#ctl").val() == "1" && $('#ctlapp') != ""
OR
$("#ctl").val() == "0"
if (
!(
$finishBoxes.length == $finishBoxes.filter(':checked').length
&&
$('#tcaccept').val() == '1'
&&
(
($("#ctl").val() == "1" && $('#ctlapp') != "")
||
$("#ctl").val() == "0"
)
)
)

Related

Form is submitting even after failing Javascript validation?

I have a form called here:
<span class="aligncenter button">Submit</span>
And I have a JavaScript function here:
if (myForm == 'newIncident')
{
var vDemAge = document.forms['newIncident']['demAge'].value;
var vBibNumber = document.forms['newIncident']['bibNumber'].value;
// Run through validations before submitting form
validateTime();
validateDate();
validateAge();
validateGender();
validateLocation();
validateType();
validateDisposition();
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
else
{
document.getElementById(myForm).submit();
}
So I have each of the validations as a separate function that I am calling in sequence when submitting the form. If I comment out the "document.getElementById(myForm).submit();", the validations run as expected. However, if I leave it uncommented, it submits every time even if the validations fail. How can I stop this from happening?
Thanks!
EDIT:
So this is one of the validations I'm running. They're all structured the same way. Somewhere I should be returning a boolean true/false? How exactly would I insert that in this one below?
function validateDisposition()
{
var vIncidentDisposition = document.forms['newIncident']['incidentDisposition'].value;
if (vIncidentDisposition == '')
{
document.forms['newIncident']['incidentDisposition'].className = 'required';
}
else
{
document.forms['newIncident']['incidentDisposition'].className = 'formborder';
}
}
assuming your validation functions return a bool, you should have something like
if( validateTime() && validateDate() && validateAge()... etc ) {
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
I got it working! The boolean idea put me on the right path. Thanks!
I just added a "return true" and "return false" to each of the validations, then used the answer above with the "&&" if to build the logic into the myform "if". If it doesn't pass all of them the else does a "return false". Works like a charm!

Javascript Conditions are Executing Either Way

please help me out on this, I realy don't figure out where is the problem.
my code:
function validateForm()
{
var pic = document.getElementById("photo1").value;
pic = pic.split('/').pop().split('\\').pop().replace(/[.][^.]+$/, "");
var x = document.getElementById("gyuruszam");
var gyuru = document.getElementById("gyuruszam").value;
if (gyuru == null || gyuru == "" || gyuru == " ")
{
alert("Gyűrűszám nélkül nem lehet adatot lementeni!");
x.focus();
x.style.borderColor="#C30";
return false;
}
if ((gyuru != pic) && (pic != NULL)){
alert("A kép neve nem egyezik meg a gyűrűszámal!");
return false;
}
}
I don't know why is executing the second if, if I do not select file on the field.
I just want an if condition, if I select file and the gyuru is not equal with the name of the file, then return false with an error message. But if I don't select a file return true(ornot even entering in the loop)
Thank you in advance!
EDIT:
I also try this way:
function validateForm()
{
var pic = document.getElementById("photo1").value;
pic = pic.split('/').pop().split('\\').pop().replace(/[.][^.]+$/, "");
var x = document.getElementById("gyuruszam");
var gyuru = document.getElementById("gyuruszam").value;
if (gyuru == null || gyuru == "" || gyuru == " ")
{
alert("Gyűrűszám nélkül nem lehet adatot lementeni!");
x.focus();
x.style.borderColor="#C30";
return false;
}
else if ((gyuru != pic) && (pic != NULL)){
alert("A kép neve nem egyezik meg a gyűrűszámal!");
return false;
}
}
it's working, but not like I want, because if I upload a file with different name, not equal with gyuru it's return true.
my form data is:
<form...
<input type="text" id="gyuruszam" name="gyuruszam"/>
<input type="file" id="photo1" name="photo1"/>
../form>
AND i CHECK THE RETURNED FILE NAME pic IT'S CORRECT!
I'm sorry I'm not sure of what you want.
Your code has a mistake, NULL does not exists, you should put null.
Second problem: pic cannot be null, it will be an empty string if you don't select a file.
So I guess you are looking for:
} else if ((gyuru != pic) && (pic != null) && (pic != '')) {
Try it here: http://jsfiddle.net/nyothecat/ALjGJ/

javascript form validation with multiple if statements

is this form validation function correct? or it can be done better ?
For example: I want one of the two drop-downs to have a value before checking the contact details fields, (dp1 OR dp2) but even though using ( || ) the validation is acting as &&.
$('#send').click(function(){
if( document.downloadForm.SoftwareDp.value == "0" || document.downloadForm.ManualDp.value == "0" )
{
alert( "Please Select a file for Download" );
return false; }
// First check if Dropdown 1 OR dropdown 2 have been selected ( ONE at least)
if( document.downloadForm.name.value == "" && document.downloadForm.email.value == "" )
{
alert( "Please enter your details" );
return false; }
// then check if name and email are typed in.
else{ // run some ajax if above conditions are met } });
Demo : http://jsbin.com/UGotAFIL/1/edit?html,js,output
Thanks
Your condition working perfectly.
If you want to check both drop down are not selected you should use && instead of ||.
If you need to select at least one drop down means you can you can use
$('#send').click(function(){
if(!( document.downloadForm.SoftwareDp.value != "0" || document.downloadForm.ManualDp.value != "0" ))
{
alert( "Please Select a file for Download" );
return false; }
// First check if Dropdown 1 OR dropdown 2 have been selected ( ONE at least)
if( document.downloadForm.name.value === "" && document.downloadForm.email.value === "" )
{
alert( "Please enter your details" );
return false; }
// then check if name and email are typed in.
else{ // run some ajax if above conditions are met
} });
see this jsbin demo
If I understand you correctly, you want to show the error when no dropdown has a value, that is both have no value.
Change
if( document.downloadForm.SoftwareDp.value == "0" || document.downloadForm.ManualDp.value == "0" )
to either
if( document.downloadForm.SoftwareDp.value == "0" && document.downloadForm.ManualDp.value == "0" ) // both have the default value 0
or
if(!( document.downloadForm.SoftwareDp.value != "0" || document.downloadForm.ManualDp.value != "0" )) // none of them has not the default value
The way you are checking will always give alert unless you select other than 0 values in both.
You should do it this way:
if( document.downloadForm.SoftwareDp.value == "0" && document.downloadForm.ManualDp.value == "0" )
The above will give alert only when both are selected for 0. If one of them has other value it won't display alert.

Javascript if else help for handler

Now the form is one form, here is the new broken code
<script language="javascript" type="text/javascript">
function verifyIt(){
if((document.form1.baseline_08.value != "" && Number(document.form1.baseline_08.value) && document.form1.baseline_08.value != "-1")){
if((document.form1.baseline_09.value != "" && Number(document.form1.baseline_09.value) && document.form1.baseline_09.value != "-1")){
document.form1.submit();
return true;
}else{
alert("Please select how old you were when you started smoking every day.");
return false;
}
}
function submit2(){
document.form1.direction.value = "back";
document.form1.submit();
}
</script>
Now the verify doesnt work at all. I just dont see what is wrong with this now.
The problem I am having is the form1 is the only one being recognized. I believe it is because of my if statement structure. Basicly I only get the return from the form1. What is wrong with my js?
I believe it is because of my if statement structure.
Yes, you are always returning after checking form1. However, you cannot submit multiple forms at a time, so you should combine them into one. Then use
function verifyIt() {
if(!(document.form.baseline_08.value == "" && Number(document.form.baseline_08.value) && document.form.baseline_08.value != "-1")){
alert("Please select how old you were when you started smoking every day.");
return false;
}
if(!(document.form.baseline_09.value != "" && Number(document.form.baseline_09.value) && document.form.baseline_09.value != "-1")){
alert("Please select when you would smoke after waking up.");
return false;
}
document.form.submit();
}

Radio Button, Text Area and Input check

I have a form with all the input fields as class item. When I click submit, it checks, with the following function if all values are filled in.
$.each($(".items"),function(i,e){
// loop through all the items
if(e.value == "" || !$("input[name='"+e.name+"']:radio:checked").length)
if(error.indexOf(e.title) === -1)
error += e.title + "<br/>";
});
This form comprises of text areas, radio boxes and normal text input fields. It returns all the radio boxes not filled in, as well as all the text inputs not filled in. But then it also returns ALL the text areas, regardless of whether it's filled in or not.
I first thought it was because I specified it to check the value, but it seems the value check does in fact check text areas, so it can't be that.
Could anyone assist me in making it return only empty elements?
$.each( $( '.items' ), function() {
if ( ( this.type === 'checkbox' || this.type === 'radio' ) && !this.checked ) {
// Go
}
else if ( this.value === '' ) {
// Do your stuff
}
});
Unfortunately, it seems there is no other choice but to separate the cases.
$.each($('.items'),function(i,elem){
if( ($(elem).attr('type') == 'radio' || $(elem).attr('type') == 'checkbox') && !$(elem).is(':checked') ) {
// RADIOS AND CHECKBOXES EMPTY
} else if( $(elem).val().length == 0 ) {
// INPUTS TYPE TEXT AND TEXTAREA EMPTY
}
});
So I used a combination of JBRTRND and Florian Margaine's answers as neither wanted to work 100% correctly.
I just put this here incase someone is stuck on the same issue. I in no way take credit for ANY of the help I received from them and I'm really thankful for it.
This is how I fixed it:
$.each($(".items"),function(){
// loop through all the items
// and alert the value
if ( this.type == 'radio' && !$("input[name='"+this.name+"']:radio:checked").length) {
if(error.indexOf(this.title) === -1)
error += this.title + "<br/>";
}
else if ( this.value === '' ) {
if(error.indexOf(this.title) === -1)
error += this.title + "<br/>";
}
});

Categories

Resources