This is just a simple JavaScript form-validation that i put together, all the document.form.*.value exist on my page, except for the document.form.dasdasdas.value ==''
In the following code, with the point of it being to give an error if any of the forms are empty, in this case however, because i assume dasdasdas is not a form on my page, it doesn't, and my question is why.
Even though it doesn't exist, doesn't that make it empty?
My question is: Why does, after i filled everything in ( customername to customerpostcode ) and leave customerbank and customercity empty, it still says everything is oke ?
After deleting that line everything works just fine, but i'm curious to why it behaves like this!
An answer to this, not so good explanation would be, awesome!
Here is my code.
function FileChecked()
{
if( document.form.customername.value =='' ||
document.form.customerpassword.value =='' ||
document.form.customerphone.value =='' ||
document.form.customeremail.value =='' ||
document.form.customeradres.value =='' ||
document.form.customerpostcode.value =='' ||
document.form.dasdasdas.value =='' ||
document.form.customerbank.value =='' ||
document.form.customercity.value =='')
{
alert('Not all forms are filled.');
return false;
}
// Check if file is selected and extension is .csv
if(document.form.csvfile.value =='')
{
alert('No file given');
return false;
}
else
{
ext = document.form.csvfile.value.toLowerCase();
if(ext.substr(ext.length-4) == '.csv')
{
return true;
}
else
{
alert ('Filetype is not .csv');
return false;
}
}
}
If document.form.dasdasdas doesn't exist, then it's undefined. You can't get the property value of undefined - hence the error.
You'd want to do something like
... || (document.form.dasdasdas === undefined || document.form.dasdasdas.value == '') || ...
but like i said, if document.form.dasdasdas doesn't exist on the DOM then it'll be pretty hard for someone to fill it in.
When you try to get the value property of an element then it should be exist on the page or in DOM itself.
document.form.dasdasdas
I believe here you are trying to get a value of an non existing element so when you are trying to get it's value property it gives you undefined.
To avoid this first you need to check this for undefined and then get it's value and do your comparision
(document.form.dasdasdas != undefined || document.form.dasdasdas.value == '')
Related
I would like to be able to skip checking a variable if the property (.emailAddress) has the chance of being undefined but continue checking the others.
For example, I'm checking an entered email address if its an existing contact (email) on the page.
if(inputEmail.length > 0 && inputEmail.indexOf('#') > 0 */ check that the input is not blank & is probably an email address.
&& inputEmail !== existingContact1.emailAddress
&& inputEmail !== existingContact2.emailAddress
&& inputEmail !== existingContact3.emailAddress
&& inputEmail !== existingContact3.emailAddress
) {
// execute code
}
My problem occurs if .emailAddress is undefined, as you can't check undefined in an If statement.
.emailAddress could be any combination of existingContact 1-4 that could be undefined or not.
can’t check should read can’t compare undefined.
I've tried using typeof to find if it is undeclared with not the results I was expecting.
&& typeof existingContact1 == "undefined" || typeof existingContact1.emailAddress == "undefined" && existingContact1.emailAddress !== inputEmail
What are some diffrent approaches to be able to anticpte and skip over if .emailAddress has the chance of being undefined?
In programming undefined & null evaluate/return to false, so check like this
if(inputEmail && inputEmail.indexOf('#') > 0 */ check that the input is not blank & is probably an email address.
&& inputEmail !== existingContact1.emailAddress
&& inputEmail !== existingContact2.emailAddress
&& inputEmail !== existingContact3.emailAddress
&& inputEmail !== existingContact3.emailAddress
) {
// execute code
}
try the approach like
var existingContact1 = { emailAddress: 'abc#zyz.com' }
var existingContact2 = { emailAddress: 'abc#zyz.com' }
var existingContact3 = { emailAddress: 'abc#zyz.com' }
var existingContact4 = { emailAddress: 'abc#zyz.com' }
if(inputEmail.length > 0 && inputEmail.indexOf('#') > 0 */ check that the input is not blank & is probably an email address.
&& [existingContact1, existingContact2, existingContact3, existingContact4]
.map(({ emailAddress }) => emailAddress) // get existing emails
.filter(x => x) // remove falsy values if any
.indexOf(inputEmail) > -1 // check if available
) {
// execute code
}
The wonderful thing about javascript is you can work with undefined. I highly recommend keeping everything as simple as possible at all times. Let's cover some cases:
You can literally assess with === operator if something is undefined. === returns true when the values on both sides are equal in value and type, which is how you'd check if a value is not defined in the most explicit way.
You can use a lazy falsy check, which is actually what I recommend. Using !!x (or just x in an If statement) will coerce it to boolean, and it will return true if x is a non-empty string and is not undefined.
I want to add as a footnote that I would recommend just keeping an array called emailsOnPage and then checking if input.email is in the array, rather than manually checking 4 conditions.
Robin mentioned the case insensivity of emails, and that's easy to do; just use the form if(x.toLowerCase() == y.toLowerCase()).
if(something.food == true){
if(something.food.fruit == 'apple' || something.food.fruit == 'mango'){
//do something
}
}
this is clear where food must be true later check it's child object, but how to write this in one line? I mean with single if.
If something.food is true then it can not be an object containing fields as well. Though your current check does check for a "truthy" value, it reads quite strange (thanks for pointing this out T. J. Crowder). Instead you should just leave out the == true part.
The resulting check is:
if (something.food && (something.food.fruit == 'apple' || something.food.fruit == 'mango') {
//do something
}
That's all
if(something.food && (something.food.fruit == 'apple' || something.food.fruit == 'mango')) {
//do something
}
As a petition in the comments, I will explain that.
First we check something.food without == true because we need to check if it exists. Then wrap the rest of code into parenthesis and the expression will run ok
I'm really trying to avoid nesting in this code snippet...
deal_trade_in_model_1 = document.getElementById('deal_trade_in_model_1').value;
deal_trade_in_amount_1 = document.getElementById('deal_trade_in_amount_1').value;
if (typeof deal_trade_in_model_1 !== 'undefined' && deal_trade_in_model_1 !== null) {
console.log(deal_trade_in_amount_1);
console.log(deal_trade_in_model_1);
if (deal_trade_in_model_1 !== null || deal_trade_in_model_1 !== "") {
if (deal_trade_in_amount_1 == null || deal_trade_in_amount_1 == "") {
console.log('entered into function');
document.getElementById("deal_trade_in_model_1").value = "";
document.getElementById("deal_trade_in_amount_1").value = "";
}
}
}
Basically, what this function does is take the value of two fields... things to know about them and what I want to do to them:
1) They're NOT required
2) If one of them is filled out, the other must be
3) If ONLY one of them is filled out, the user clicks submit, and this part of the function is called upon, I want to delete the value of both of them.
I've tried doing a compound of
&& (and)
and
|| (or)
buttttt it odiously it didn't work.
Primary question: What's the best way to get rid of the nesting (I planned on doing this twice and just swapping the code) that will be the most efficient? This, I want, to be done preferably in the smallest amount of IF statements possible.
Please note: If you change the code a lot, I might not know what you're talking about.. please be prepared to teach me or help me learn!
It sounds like you only want to do something if either of the fields are empty, but not both. Assuming both of the elements are text fields, .value will always return a string. Converting a string to boolean results in false if the string is empty, otherwise true.
So
Boolean(deal_trade_in_model_1) === Boolean(deal_trade_in_amount_1)
will be true if either both fields have a value (both will convert to true) or both fields are empty (both convert to false).
Thus your code can be reduced to
var model_1 = document.getElementById('deal_trade_in_model_1');
var amount_1 = document.getElementById('deal_trade_in_amount_1');
if (Boolean(model_1.value) !== Boolean(amount_1.value)) {
model_1.value = "";
amount_1.value = "";
}
I'm trying to make a page where you fill in some input boxes and check a radio button, and if you complete all of it, you can click a div, and animations happen. The specific input boxes are not the only ones on the page. I'm trying to use a javascript "if" statement that has a bunch of "and"'s and an "or" in parentheses, but when I open the page, the code doesn't run. This isn't all my code, and I know the javascript and it's libraries are linked because I've been coding this site for a while, and everything has worked up until now. I checked the code in a javascript validator and it seemed fine. I'm not sure what I'm doing wrong.
$(document).ready(function(){
if ( $(".managementCompanyName").val() !== '' &&
$(".approvedBy").val() !== '' &&
$(".contractStartDate").val() !== '' &&
$(".proposalNumber").val() !== '' &&
$(!$("input[name='proposalReviewedForInvoice']:checked").val() || !$("input[id='proposalNotReviewedForInvoice']:checked").val()) ) {
//do stuff
}
});
Alternatively I have
$(document).ready(function(){
if ( $(".managementCompanyName").val() !== "" &&
$(".approvedBy").val() !== "" &&
$(".contractStartDate").val() !== "" &&
$(".proposalNumber").val() !== "" &&
$("input[name='proposalReviewedForInvoice']:checked").val() !== "" ) {
//do stuff
}
});
This code seems to work on another part of the site where there's only one input as a requirement.
Thank you if you can spot my error.
Wrap the || part in parentheses, otherwise the first operand to || is actually the last result from the last &&.
/*$*/(!$("input[name='proposalReviewedForInvoice']:checked").val() ||
!$("input[id='proposalNotReviewedForInvoice']:checked").val()) ) {
And actually it seems that you rather had them wrapped in a $(), which will always return a jQuery object, which will always be "truthy" in the condition.
for handling errors much better if you only used the "OR (||) " condition.
$(document).ready(function(){
var management = $(".managementCompanyName").val();
var approved = $(".approvedBy").val();
var contract = $(".contractStartDate").val();
var proposed_num = $(".proposalNumber").val();
var proposed_rev = $("input[name='proposalReviewedForInvoice']:checked").val();
if ( management == '' || approved == '' || contract == '' || proposed_num == ''
|| proposed_rev == '' ) {
// error message
} else {
// do stuff
}
});
Whats wrong with the below lines of code ...
Its keep complaing that systax error..at the like
if( (radioval === "undefined") || (radioval === null) || (radioval === "null") ) {
complete condition in action
if($('#digitallogin').is(":checked")){
var radioval = $("input[name=certificateradio]:checked").val();//its giving the string "user"
if( (radioval === "undefined") || (radioval === null) || (radioval === "null") ) { //this line
$("#login_error").text("please select the signin certificate");
return false;
}
}
Thanks for any Assistance.
There's no syntax error in your code. If the code had a syntax error, there would be an error message in the Firebug console (not the Watch panel), and the code would not run at all. You'd never get to your breakpoint.
The syntax errors in your screenshot are in your watch expressions. Delete the watch expressions and those error messages will go away.
In your updated screenshot I can see what the syntax error is. Take a close look at your watch expression (reformatted here to avoid scrolling):
if(
(radioval === "undefined") ||
(radioval === null) ||
(radioval === "null")
)
That's not an expression, it's an if statement. If you want to use it as a watch expression, you need just the expression inside the if statement. That is, remove the if( and the final ).
Regarding the specific tests you're making, jQuery's .val() method does return undefined if there are no elements selected. Note that there is an error in the jQuery documentation: it says that .val() returns null when there are no matching elements. This is incorrect; it returns undefined in this case. Here is the line of code in the jQuery source that returns undefined (because it is a simple return; with no value).
But that is the undefined value, not the string "undefined". You would test for this with radioval === undefined. Or you could use radioval == null. Note the == instead of ===; this test matches both null and undefined values. That may be the safest bet, in case the jQuery team ever decides to change the code to match the documentation and start returning null instead of undefined. (An unlikely possibility, but you never know.) By testing radioval == null it would test against either value.
Try
if( (typeof radioval === "undefined") || (radioval === null) || (radioval == "null") ) {
in the third comparison of radioval
radioval == "null" and not === null
$("input[name=certificateradio]:checked").val(); returns undefined (typeof undefined === undefined) if it's unchecked or "on" (typeof "on" === string) if it's checked.
a small example:
<input name="certificateradio" type="checkbox" />
<button>run</button>
$("button").click(function(){
console.log($("input[name=certificateradio]:checked").val());
console.log(typeof $("input[name=certificateradio]:checked").val());
});
http://jsfiddle.net/x2uw4/1/
try to use:
if($("input[name=certificateradio]:checked").val() ==="on"){
...
}
.val() returns a string value, null or an Array in case of a multiselect value, so you could try:
if (/null|undefined/i.test(radioval) || !radioval.length){ /*...*/ }
Since you seem to check for [one of] $("input[name=certificateradio]") being checked, it may also be sufficient to do
if( ( !$("input[name=certificateradio]:checked").length ) {
$("#login_error").text("please select the signin certificate");
return false;
}
Or even shorter
if( $('#digitallogin').is(":checked") &&
!$("input[name=certificateradio]:checked").length ) {
$("#login_error").text("please select the signin certificate");
return false;
}