javascript null value not working - javascript

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.

Related

Checking for null is not working for ajax json data

I am getting data from ajax call like
[{"_id":{"$oid":"5bd00e99d2ccda119c0032da"},"AllotmentsDetails":null}]
I am comparing it for null value like
var allotmentDetailsArray = data[0]['AllotmentsDetails'];
if (allotmentDetailsArray.length == 0 || allotmentDetailsArray == null)
{
////
}
It is not going in if condition... Please help !!!
You have to check against null before trying to access the object, in your if block you are trying to call .length on a null object.
You can do it like this:
if (!allotmentDetailsArray || allotmentDetailsArray.length == 0)
{
////
}
Where !allotmentDetailsArray is a shortened expression for allotmentDetailsArray == null which checks that allotmentDetailsArray is undefined or null.
So here the second part of the if block is only checked when allotmentDetailsArray is not null.
You have to check null first then check for length
if (allotmentDetailsArray == null || allotmentDetailsArray.length == 0)
{
////
}
You cannot check length of a null value. However you can check null value and array length with this code.
if (!allotmentDetailsArray) {
// null check here. you cannot check array length here since it's a null value
} else {
// if you want to check array length
if (allotmentDetailsArray.length === 0 ) {
// check here
}
}
First you have to check null or not null. if its not null means then check length.
Please try it.
//Ex:1
var data= [{"_id":{"$oid":"5bd00e99d2ccda119c0032da"},"AllotmentsDetails":null}];
var allotmentDetailsArray = data[0]['AllotmentsDetails'];
if (allotmentDetailsArray == null)
{
alert(allotmentDetailsArray);
}
else if(allotmentDetailsArray.length == 0)
{
alert(allotmentDetailsArray.length);
}
//or
if (allotmentDetailsArray == null ||allotmentDetailsArray.length == 0 )
{
alert(allotmentDetailsArray);
}
//Ex:2
var data= [{"_id":{"$oid":"5bd00e99d2ccda119c0032da"},"AllotmentsDetails":""}];
allotmentDetailsArray = data[0]['AllotmentsDetails'];
if (allotmentDetailsArray == null)
{
alert(allotmentDetailsArray);
}
else if(allotmentDetailsArray.length == 0)
{
alert(allotmentDetailsArray.length);
}
You can just check the type:
var allotmentDetailsArray = data[0]['AllotmentsDetails'];
if (typeof allotmentDetailsArray !== "undefined")
{
// Var is not null
}

Adobe Acrobat 2017 Javascript is null?

In this code:
this.getField("myField").value == null;
this.getField("myField").value === null;
typeof this.getField("myField").value == null;
typeof this.getField("myField").value === null;
this.getField("myField").rawValue === null;
this.getField("myField").formattedValue === "";
this.getField("myField").isNull;
this.getField("myField").isNull == True;
all of the above exchanging 'null' for 'Null', encapsulated 'Null', and 'undefined'.
In each circumstance all I get is:
TypeError: this.getField(...) is null
23:Field:Blur
How do I see if a field is null? I do not want to have default values because not every field on the form needs to be used and should be able to be blank.
If you're getting that error, it's because this.getField("myField") itself is returning null. So any attempt to use a property on what it returns will fail.
It sounds like you need a null guard:
var field = this.getField("myField");
if (field !== null) }
// use `field.value` here...
}
Generally... meaning you used an application rather than a library to create the form... PDF field values will never be null. An empty field has a zero-length string as the default value. To test if the field is empty use...
if (this.getField("myField").value.length == 0) {
// do something
}
else {
// it has a value
}
or
if (this.getField("myField").value == "") {
// do something
}
else {
// it has a value
}

using if statement with && and || inside for loop

I have an if statement inside for loop with more than one condition. I want to match the data in database with input data in an HTML form. When the input field in the form is blank it is stored as null in the database. I have this column(itemsSortedByDate[i].FD_MIMO) in the database which can be null or can have some value. I am unable to match the blank field with null in the database. Also even if that column(itemsSortedByDate[i].FD_MIMO) has some value in the database, my for loop searches for the database which has null field just because other fields are matching. My Javascript is as below. The last condition is creating problems. ScenarioListViewModel.fdMimo()and itemsSortedByDate[i].FD_MIMO are supposed to be same whether it's null or has some value. But in the console.log they are different. Thank you for your help, much appreciated.
self.getJobIdForCapacity = function(itemsSortedByDate){
var jobIdForCapacity;
var found = false;
for (var i = 0, len = itemsSortedByDate.length; i < len; i++) {
if(itemsSortedByDate[i].DB_Name == ScenarioListViewModel.db_name()
&& itemsSortedByDate[i].Split_Mode == ScenarioListViewModel.splitMode()
&& itemsSortedByDate[i].Full_Output == ScenarioListViewModel.fullOutput()
&& (itemsSortedByDate[i].Workflow_Status == "Completed" || itemsSortedByDate[i].Workflow_Status == "Running")
&& (itemsSortedByDate[i].Disposition == "Success" || itemsSortedByDate[i].Disposition == "None")
&& (itemsSortedByDate[i].FD_MIMO == ScenarioListViewModel.fdMimo() || itemsSortedByDate[i].FD_MIMO == null)){
jobIdForCapacity = itemsSortedByDate[i].Title;
console.log("Job Id:" + jobIdForCapacity);
console.log("fdmimo from form:" +ScenarioListViewModel.fdMimo());
console.log("fdmimo from list:" +itemsSortedByDate[i].FD_MIMO);
self.getJobResults(jobIdForCapacity);
found = true;
break;
}
}
if (!found) {
alert("Job not found in Sharepoint Execution History List. Click Execute Model to run");
}
};
I would suggest you use === in all the conditions in if statement and it may help you solve your problem as there is difference in === vs ==.
Please refer this question for the difference.
For example:
itemsSortedByDate[i].DB_Name == ScenarioListViewModel.db_name()
will be
itemsSortedByDate[i].DB_Name === ScenarioListViewModel.db_name()
Condition:
"Completed" || itemsSortedByDate[i].Workflow_Status == "Running"
will always return "Completed" does not matter itemsSortedByDate[i].Workflow_Status == "Running" is true or false. Here your can use ternary operator like
itemsSortedByDate[i].Workflow_Status == "Running"? "Running" : "Compelted"
Something of this kind. Check all conditions like this.

|| operator not setting default when null

I am running this line:
var good = data["good"] || false;
where data comes from the success method in a jquery ajax request.
But, what I thought that this would do is default good to false if data["good"] is null, but it is not.
Chrome is throwing this:
Uncaught TypeError: Cannot read property 'good' of null
and since it is null, shouldn't good then be set to false?
The problem is not that data["good"] is null, but that data itself is null.
Your code as is would be fine if data always has a value, but may not have property good. But unfortunately the JavaScript engine doesn't check if everything in a statement is undefined or null, i.e. it won't test data, and then test data["good"] and so on.
You need to test if data has at least some sort of value first, that is, it is "truthy".
Fix 1
You can lay it out clearly like so:
var good = false;
if(data && data["good"]) {
good = data["good"];
}
Fix 2
Or a neat shortcut is to use the fact that && and || will return the first "truthy" value found - it does not have to be a boolean:
var good = (data && data["good"]) || false;
The jquery tutorial on Operators has a good explanation of what is returned from the && and || operators.
// has a value - sets to "foo"
var data1 = { good: 'foo' };
var good1 = (data1 && data1["good"]) || false;
document.write("<div>" + good1 + "</div>");
// data is null - sets to false
var data2 = null;
var good2 = (data2 && data2["good"]) || false;
document.write("<div>" + good2 + "</div>");
// data["good"] doesn't exist - sets to false
var data3 = { bad: 'hello' };
var good3 = (data3 && data3["good"]) || false;
document.write("<div>" + good3 + "</div>");
Falsy Gotchas!
The other thing to be careful of is that some values you would want to store in your variable may evaluate to false, so you might incorrectly end up with good = false. This depends on what you expect to be inside data["good"].
This will occur for the following, again from the jquery site:
false - boolean false value
"" - Empty strings
NaN - "not-a-number"
null - null values
undefined - undefined values (i.e. if data doesn't have property "good")
0 - the number zero.
If you think this could be the case, you may need to be more specific in your checks:
var data = { good: 0 };
// 0 is falsy, so incorrectly sets to false
var good = (data && data["good"]) || false;
document.write("<div>" + good + "</div>");
// check the actual type and value - correctly set to 0
var good2 = (data && (typeof data["good"] != "undefined") && data["good"] != null)
? data["good"] : false;
document.write("<div>" + good2 + "</div>");
In your case, I can't imagine one-liner, which will check if data is not null and if so, put data[good] into variable.
You must first of all, get rid of Exception.
I would rather do:
var good = false;
if(data){
good = data["good"] || false;
}

Jquery string and logical OR

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;
}

Categories