JS If/Then to Remove NULL Value - javascript

I have a very simple JS script that is embedded into an email. The goal is to autopopulate the salutation of the email and is as follows.
if (Contact.Field("firstname") == "NULL") {
document.write(Contact.Field("custname"));
} else if (Contact.Field("firstname") == "") {
document.write(Contact.Field("lastname")"Household");
}
The problem I'm running into is that the script will still autopopulate the NULL value in the email instead of switching to the "custname" field when it runs. I'm sure this is due to user error, but if anyone could help steer me in the right direction I would greatly appreciate it. Thanks!

You have used "NULL" in the if statement, where you should have used null (without quotes, and in lowercase letters.) on it's own, like this:
if (Contact.Field("firstname") == null) {
document.write(Contact.Field("custname"));
} else if (Contact.Field("firstname") == "") {
document.write(Contact.Field("lastname")"Household");
}
Using "NULL" would check if the text in Contact.Field("custname") was the string "NULL", rather than checking if it has no content.
As to whether to use == or ===, you can find an answer here: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Related

js doesn't execute 'else' statement

I have an if-else statement in JavaScript which returns false, but doesn't execute the code inside 'else'.
part of the script inside the cshtml file:
if (#Session["mission"].ToString() != "1") {
setInterval(function () { myTimer(ctxPoints, ctxLines); }, 1000 / #ViewBag.rate);
} else {
alert("hi");
}
In the debug the '#Session["mission"].ToString() != "1"' statement returns false, but nothing jumps to the screen.
You should open your web browser Developer console and see the real script which reaches the browser.
The Razor parts, #Session["mission"].ToString() doesn't exists in the browser script, because they are evaluated in the server, before sending them to the browser. So it makes no sense to try #Session["mission"].ToString() != "1" this in the console. In the browser you will get something like:
if (1 != "1")
or even like
if ( != "1")
which would provoke an error.
JavaScript does coalescing, so 1 is equal to "1" when you use the comparers == or !=, so you don't need to include the qoutes around the value (unless you get the error mentioned above: in this case, if you included the quotes, you'd get if ("" != "1")).
Coalescing is avoided by using the !== or === which would consider 1 not equal to "1", so, including the quotes doesn't make any difference in this case.
I think you should clear Js code and c# code
if ("#Session["mission"].ToString()" != "1")
Session["mission"].ToString() this print string in c#, but you need to encapsulate it in quote to make this value get type string

Boolean and text field validation - Javascript

I have a form that posts to itself with a text field (for SMS number) and a boolean field (for SMS opt in). I can't seem to get the syntax correct for validation when the end-user goes to post the form.
If they select the bool for opt in, then the form should check the text field for the sms number and if the sms number is empty, display an error.
Here's my javascript snippet:
if (document.getElementById("smsOpt").checked = 'true' && document.getElementById("smsNum").value = ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
You can do something like this:
if (document.getElementById("smsOpt").checked && document.getElementById("smsNum").value.trim() == ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
For checkbox, the checked property is of type boolean so use of only "checked" is fine. And for the second property you can compare it with an empty string. Single = operator in JS is for assignment and not comparison.
You have to use == or === instead of = in vary conditions.
if (document.getElementById("smsOpt").checked == 'true' && document.getElementById("smsNum").value == ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
There is actually no need for using any equality operators in this case. You can do something like this:
if (document.getElementById("smsOpt").checked && !document.getElementById("smsNum").value){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
But if you want to use them, then do it with triple === or double equality == operators. You can check the differences between theese two here.
In JavaScript = is only for assignment, so your if-statement is setting checked=true on the input rather than checking what is it. (Or it actually sets it to true no matter what it was and then evaluates the result of setting the value which will always be true)
You need to use == or better ===
if (document.getElementById("smsOpt").checked === true && document.getElementById("smsNum").value.trim() === '') {
I added trim() also so it ignores if you just insert spaces.

Weird Javascript If Statement

I'm not sure whats wrong with my if statement. I'm trying to use my model inside my javascript.
if (#Model !== null)
{
if (#Model.Level !== null)
{
//use #Model.Level
}
}
else
{
//use default
}
The Model is null, but it still steps into the first if statement (and breaks on the second one obviously). I've tried #Model, !#Model and != but it still always steps in.
What am I doing wrong? (It's also got squiggly red lines under both !== saying there is a syntax error)
Triple equations work without type castings in JavaScript. In your case you are might get an undefined object which isn't a null value.
For example:
undefined === null //Do not cast when comparing, increased performance.
false
undefined == null //Do cast when comparing, decreased performance.
true
In addition, if #Model value is null then you won't see a null value on client side. It gives you an empty value like this:
if( == null)
{
}
This will cause an error on your javascript side. Null check should be done at server side. For that reason you have to put # value in front of your code to make it server side:
<script>
#if (Model != null) //Server side code.
{
if (Model.Level != null) //still server side code.
{
<text>
alert("your javascript here"); //write javascript on your screen.
</text>
}
}
</script>
In order to check if something is null or undefined in javascript, use if (#model) rather than if ( #model !== null)
http://appendto.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/
The reason why it steps into the if statement is because it evaluates to true, no weirdness to be found here. Your browser is not temperamental. For a list comparisons check out this http://dorey.github.io/JavaScript-Equality-Table/
Also note that there is a difference between double and triple =. Triple will type cast
This code looks a LOT like a Razor then Javascript, though you may be trying to mix the two of them together.
Your choices:
1) Convert Model to a JavaScript object using something like this:
Turn C# object into a JSON string in .NET 4
2) Use the Razor if statement and write out your final JavaScript with it.
<script>
// Code assume this is an numeric value
var useThisVariable;
</script>
if (#Model !== null)
{
if (#Model.Level !== null)
{
<script>
useThisVariable = #Model.Level;
</script>
}
}
else
{
<script>
useThisVariable = -1;
</script>
}

Evaluate prompt value wont

I'm very new to JS - only a couple days in.
Trying to write a very basic prompt evaluated by an if statement.
When I run the code below, the user is prompted, but the statement is never evaluated by the if statement.
Any help? -- I realize the answer is probably simple and obvious, but as a SUPER beginner, what do I do?
var bool = prompt("What is an example of a boolean?");
if (typeof(bool) === "boolean") {
print("correct! that is a boolean");
print(bool) ;
};
In this case, assuming the user inputs something in the prompt, the type of the bool variable will always be a string. You'd rather check if the input compares to the string "true" or "false" etc., like this:
if (bool.toLowerCase() == "true" || bool.toLowerCase() == "false") {
...
}

Javascript only checks one field

Ok so I've been stumped on this one for days and its frustrating me. (Will frustrate me even more if it's something simple I'm overlooking).
I have a form generated in PHP which I want to verify that certain pieces are filled out. I do this via a JavaScript check when the user clicks the submit button.The JavaScript code is below:
<script language="JavaScript">
function checkFields()
{
if (document.getElementById('ldescription').value == '' || document.getElementById('uname').value == ''
|| document.getElementById('sdescription').value == '' || document.getElementById('email').value == ''
|| document.getElementById('platf').value == "Select Group" || document.getElementByID('cate').value == "Select Category" )
{
alert("Please fill out all of the starred (*) items" );
return false;
}
}
</script>
For some reason though this only checks the ldescription field. If that field has text but all the others are empty it carries on like everything was filled out. Also if I change the order of my checks and ldescription is anywhere but the first check, it will do no check whatsoever even when all the fields are empty.
Any ideas?
EDIT:
Got it fixed. Along with the suggestion I marked as correct the document.getElementById('item').value command worked with only textarea boxes but not regular text input boxes. By changing the command to document.MyForm.myTextName.value everything fell into place.
Couple of problems i noticed with your sample code.
The last getElementById call has improper casing. The final d is capitalized and it shouldn't be
Comparing the value to a string literal should be done by === not ==.
JSLint complains there are line break issues in your if statement by having the line begin with || instead of having the previous line end with ||.
The first and third items are most likely the ones causing your problem.
Inside your if condition, when you are breaking a line, make sure that the last token in the line is the OR operator ||.
Javascript does semicolon insertion, so it may be that semicolons are being inserted (automatically, invisibly, by the interpreter) in a bad place.
Try the below code
<script language="JavaScript">
function checkFields()
{
if (document.getElementById('ldescription').value === '' ||
document.getElementById('uname').value === '' ||
document.getElementById('sdescription').value === '' ||
document.getElementById('email').value === '' ||
document.getElementById('platf').value === "Select Group" ||
document.getElementById('cate').value === "Select Category")
{
alert("Please fill out all of the starred (*) items" );
return false;
}
}
</script>
Please use Javascript && operator which returns true if both the elements are true. || operator evaluates to true in case atleast one of the element is true which is what is happening in your case. You can take a look at Javascript boolean Logic

Categories

Resources