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;
}
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()).
When I use the below code:
if(string.match(/td>0/g).length == 8) {
/*Do something*/
}
and no /td>0/ are matched, it returns a null result that prevents the script below from executing.
I would like to know why the code is freezing, and how to avoid it and find a solution or an alternative to .match() ?
You can simply add a null check first -
if(string.match(/td>0/g) != null && string.match(/td>0/g).length == 8) {
/*Do something*/
}
Try this(More Recommended):
var matching=string.match(/td>0/g);
if( matching != null && matching.length === 8) {
/*Do something*/
}
Use === instead of ==.
You are going to need to make a null check before checking the length. I would do either do the match first and than check
var result = string.match(/td>0/g);
if (result && result.length) {}
or use an or to catch the null
if( (string.match(/td>0/g)||"").length ) {}
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
}
});
I need to check for an attribute inside the Jquery Mobile transition data object. The attribute can either be undefined or has a value of dialog or some other value.
Originally I only checked like this:
$(document).on( "pagebeforechange", function( e, data ) {
if( A && B && data.options.role != "dialog" ){
// do something
}
});
However, this way I never enter the if-clause when data.options.role is undefined. I'm currently trying like this but am not really getting anywhere:
$(document).on( "pagebeforechange", function( e, data ) {
if( A && B && data.options.role != "undefined" && data.options.role != "dialog" ){
// do something
}
});
Question
How can I make sure the value is queries and passes into the IF clause if it's either undefined or has a value, which is not dialog?
Thanks for help!
If you meant undefined type of javascript, for that you need to use typeof like this:
if( A && B && typeof data.options.role != "undefined" &&
data.options.role != "dialog" )
You also need to make sure that A and B are coming truthy too.
here's my function for checking zipcode. When a null values comes in, i keep getting "Object Required" Does anyone know where im going wrong?
aspx tags -
asp:CustomValidator
ID="cv_zipcode"
runat="server"
ControlToValidate="tb_zipcode"
ClientValidationFunction="ValidateZipcode"
ValidateEmptyText="true"
Display="Dynamic"
ValidationGroup="vgroup">
</asp:CustomValidator>
function ValidateZipcode(sender, args) {
var regZipcode = '\d{5}'
var zipcode = document.getElementById(sender.id.replace(/cv_/, "tb_"));
if ((zipcode.value == "ZipCode") || (zipcode.value.length == null) || (zipcode.value.length == "")) {
zipcode.style.backgroundColor = "#f6e086";
args.IsValid = false; return;
} else {
args.IsValid = true;
zipcode.style.backgroundColor = "white";
}
}
I'm not sure exactly which value is null, but in general, if you have a variable x which may or may not be null, and you want to do something with x, you can do the following:
x != null && do_something_with(x)
If x == null, then this returns false and doesn't try to execute do_something_with(). Otherwise, this expression returns the value of do_something_with(x).
If you just do_something_with(x), and x is null, and do_something_with() is not expecting a null, you can get errors.
EDIT:
try:
if ((zipcode == null) || (zipcode.value == null) || [everything else])
zipcode.value.length returns an integer
I think you should have
if ((zipcode.value == "ZipCode") || (zipcode.value.length == 0))
I would be a little suspect of this line:
if ((zipcode.value == "ZipCode") || (zipcode.value.length == null) || (zipcode.value.length == "")) {
Try this instead:
if ((zipCode.value == null) || (zipcode.value== "") || (zipcode.value.length == 0)) {
That error message usually indicates that you've tried to get or set a property or call a method of something that isn't an object, which tends to happen when a variable that you thought referred to an object is actuall null or undefined. That is, if someVariable is null or undefined then you can't say someVariable.someProperty.
If .getElementById() doesn't find a matching element it returns null, so in this line:
var zipcode = document.getElementById(sender.id.replace(/cv_/, "tb_"));
zipcode is potentially set to null, and if it is then all attempts to access properties of zipcode like zipcode.value and zipcode.style will fail.
If the parameter args comes in as null or undefined then attempting to set args.IsValid will fail, and similarly if the parameter sender is null or undefined then sender.id will fail.
So, if you have a variable that might be null you should test that before trying to do anything else with it.