Javascript scope in switch statement - javascript

I'm new to Javascript and don't understand the following behaviors.
When the textarea is empty, the "process" code doesn't recognize it as null, and doesn't prompt for text.
When there is text in the textarea, the "process" code does not display the text in the alert. It seems this may be a scope problem I think all my variables are global.
HTML code:
<input type="button" name="btnProcessTA" onclick="myTextArea('process')" value="Process Text Area" />
<input type="button" name="btnClearTA" onclick="myTextArea('clear')" value="Clear Text Area" />
<form id="formExample" action="" method="get">
<label for="textAreaField">A text area field</label>
<textarea name="textAreaField" id="textAreaField" rows="4" cols="50"></textarea>
</form>
Javascript code:
<script type="text/javascript">
function myTextArea(op)
{
oTextArea = document.getElementById("textAreaField");
textAreaValue = oTextArea.value;
alert(op + "\n" + oTextArea + "\n" + textAreaValue);
switch (op){
case "clear":
oTextArea.value = "";
alert("Clearing");
break;
case "process":
if (textAreaValue = "")
alert("Would you please enter some text?");
else
alert("You entered:\n\n" + textAreaValue);
break;
default : alert("unknown op code");
}
}
</script>

Change
if (textAreaValue = "")
to
if (textAreaValue === "") // or ==
You are performing assignment instead of doing a comparison.

To compare, you have to use == instead of = :)
case "process":
if (textAreaValue == "")
alert("Would you please enter some text?");
else
alert("You entered:\n\n" + textAreaValue);
break;

if (textAreaValue = "")
The single equal sign in the if statement is interpreted as an assignment (It doesn't throw an error because technically it's correct syntax, but many people make this mistake by using a single equal sign instead of the double equal sign). The correct syntax would be the triple equal sign if you are intending to compare instead of assign.
if (textAreaValue === "")

Related

Else is not executing ever

Im trying to do a form, in which you put your first name, surname and city, if inputs are empty or have number in them it should say Please fill out all of available boxes and make sure there are no numbers. Else it should say quote using all of input informations. But the else is not working.
I tried cahnging the code and swapping some variables.
function FillInfo()
{
/* proměnné */
var jmeno = document.forms ["SignUpForm"] ["jmeno"].value;
var prijmeni = document.forms ["SignUpForm"] ["prijmeni"].value;
var rok = document.forms ["SignUpForm"] ["mesto"].value;
/*Kontrola zdali input políčka jsou prázdná či pokud bylo zadáno číslo */
if(jmeno=="" || jmeno!=NaN || prijmeni=="" || prijmeni!= NaN || mesto=="" || mesto!=NaN){
document.getElementById("info").innerHTML = "Please fill out all of available boxes and make sure there are no numbers";
}
else{
document.getElementById("info").innerHTML = "Thank you" + " " + jmeno + " " + prijmeni + " from" + " " + mesto + "." + " " + "You are now being considered as our next adventurer. Good luck!";
}
}
<div class="heading2">
<div class="container2">
<p>Do you want to travel troughout space? Then fill out our form!</p><br>
<form name="SignUpForm">
<input type="text" name="jmeno" placeholder="First name" required><br>
<input type="text" name="prijmeni" placeholder="Last name" required><br>
<input type="text" name="mesto" placeholder="City" required><br><br>
<div id="info" class="well"></div>
<input type="button" class="otherpage" onclick="FillInfo();" value="Submit" /><br><br>
Return
</form>
</div>
</div>
Your if condition has to change, it always evaluates to true.
Instead of:
if (jmeno=="" || jmeno!=NaN || prijmeni=="" || prijmeni!= NaN || mesto=="" || mesto!=NaN) {
You should try:
if (jmeno==="" || isNaN(jmeno) || prijmeni==="" || isNaN(prijmeni) || mesto==="" || isNaN(mesto)) {
By the way, NaN is never equal to NaN, you have to use isNaN to know if it's a NaN.
However, this code is not what actually want. You want to check that there are no numbers, right? Depending on if you want no digits at all or no number-only values, you have to adapt your code. For example: !isNaN(Number(jmeno)) to check if the value is a number-only value. The values you get from the text inputs are always strings so the conversion is needed.
Your logic is wrong
jmeno=="" || jmeno!=NaN
Will always evaluate to true, I think you mean
jmeno=="" || isNaN(jmeno)
Obviously the rest of the statement needs editing too.

why I can not use && in javascript for not blank and not space

I want to check the value is not blank or one empty space so I wrote a code
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value != " " && OccLocation.value != "") {
alert("not empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass"
/>
You can update your condition as below.
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim() == "") {
alert("empty");
}
If you want to get alert if OccLocation is not empty then :
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim() != "") {
alert("not empty");
}
Your condition is wrong.
You have to use == instead of !=.
If you use && then both condition should be true to return true, which is ultimately impossible at the same time in this case. Use || instead, this will be evaluated as true if any of the condition is true.
The condition should be:
if (OccLocation.value ==" " || OccLocation.value == "")
Even you can simplify the condition by using String.prototype.trim()
:
The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
Try
if (OccLocation.value.trim() == "")
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim()== ""){
alert ("empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass" />
You are checking that it is not empty, then alerting that it is empty. I think you mean to check that it is empty. Change your JS to the following:
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value === " " || OccLocation.value === "")
{
alert ("empty");
}
Your code runs immediately, and the value="" sets it to empty.
Here, I set the value in the markup so it has some, thus it alerts.
var OccLocation = document.getElementById("HdnOccLocation");
console.log(OccLocation.value)
if (OccLocation.value != " " && OccLocation.value != "") {
alert("not empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="dd" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass"
/>

My Validating an input field with only characters and spaces allowed. I not that familiar with regex this is just for

The contact name input area cannot be left empty and can only have characters and spaces. I'm not that familiar with regex and my online research so far hasn't come up with a simplified explanation on how to do this.
The Regex string I have come across so far is: ^\p{L}+(?: \p{L}+)*$
But I'm not advanced enough to know how to write this as script? Can anyone help.
Thanks.
var contact_name = document.getElementById('contact');
function validate() {
if (contact_name == "") {
alert("Name name must be filled out");
return false;
}
*Do I need a new function, or can I insert script here?
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
First of all, I'm not sure in your regex, so I googled a little and found this one, which looks good: /^[a-zA-Z\s]*$/. The first issue is where you're trying to compare contact_name == "": contact_name is an element, not input's value, so it should be contact_name.value === "" instead (and I recommend to use strict equality === here). And finally you can check input's value validity via regex using regex.test(contact_name.value), which returns boolean. The solution is rather simple, but if anything isn't clear - feel free to ask.
var contact_name = document.getElementById('contact');
var regex = /^[a-zA-Z\s]*$/;
function validate() {
var isValid = true;
if (contact_name.value === "" || !regex.test(contact_name.value)) {
isValid = false;
}
alert("Is valid: " + isValid)
}
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
<button onclick="validate()">validate</button>
var contact_name = document.getElementById('contact');
var regex = /^[a-zA-Z\s]*$/;
function validate() {
var isValid = true;
if (contact_name.value === "" || !regex.test(contact_name.value)) {
isValid = false;
}
alert("Is valid: " + isValid)
}

Javascript - text input to icon

I am trying to create a simple web application. Like in Facebook chat when I enter "(Y)" it turns into the thumbs up icon. Similarly I am trying to do something like that with the following code. But it is not working for me. I am not expert with JavaScript. I need some help that what's wrong with the code?
And I made the code in a way that if i enter "y" it will return LIKE. I want to know how to show an icon after "y" input.
<html>
<head>
<title>Emogic</title>
</head>
<body>
<input type="text" id="input">
<input onclick="appear()" type="submit">
<p id="output"></p>
<script>
function appear(){
var value = document.getElementByid("input").value
var result = document.getElementById("output").innerHTML
if(value == "y"){
result = "LIKE"
}
else if(value == ""){
alert("You must enter a valid character.");
}
else{
alert("Character not recognised.");
}
}
</script>
</body>
</html>
There are a few issues/typo in your code :
it's document.getElementById(), with a capital I in Id.
result will be a string, containing the innerHTML of your element, but not a pointer to this innerHTML : when you then set result to an other value, it won't change the element's innerHTML as you expected. So you need to create a pointer to the element, and then set its innerHTML from the pointer.
The quick fix of your code would then be :
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
if (value == "y") {
output.innerHTML = "LIKE";
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="y">
<input onclick="appear()" type="submit">
<p id="output"></p>
But you'll find out that your user will have to enter exactly "y" and only "y" for it to work.
I think you should use instead String.replace() method with a regular expression to get all occurences of a pattern, i.e, for "(Y)" it could be
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
// The Regular Expression we're after
var reg = /\(Y\)/g;
// your replacement string
var replacement = 'LIKE';
// if we found one or more times the pattern
if (value.match(reg).length > 0) {
output.innerHTML = value.replace(reg, replacement);
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="I (Y) it (Y) that">
<input onclick="appear()" type="submit">
<p id="output"></p>

Javascript and HTML form validation checks

i am trying to learn html and javascript. I have created an html form and am using javascript to validate the fields. I have a isNaN check for the age field, a regex check for emial and a presence check for all fields. I am currently outputting the form to the address bar but this does not work as i am getting errors.
<title> </title>
<script type="text/javascript">
function validate()
{
var errors = 0;
if (isNumeric(document.getElementById("age").value) == false)
{
errors++;
}
if (emailCheck(document.getElementById("email").value) == false)
{
errors++;
}
var inputBoxes = document.getElementsByTagName('input');
for(var i= 0; i < inputBoxes.length; i++)
{
if(inputBoxes[i].type != 'text') continue;
if(presenceCheck(inputBoxes[i].value) == false)
{
errors++;
}
}
console.log(errors);
if(errors == 0)
{
window.location.assign("output.html#" + "%%" + "name" + "%%" +
document.getElementById("name").value + "%%" + "email" + "%%" +
document.getElementById("email").value + "%%" + "age" + "%%" +
document.getElementById("age").value + "%%" + "comments" + "%%" +
document.getElementById("comments").value);
}
}
function isNumeric(number)
{
return !isNaN(number) && number != null && number != "";
}
function emailCheck(email)
{
var emailRegex = /\s+#\s+.\s+/;
return emailRegex.test(email);
}
function presenceCheck(data)
{
var regex = /\s+/;
return regex.test(data);
}
</script>
Below is the form which is just incased in body tags at the moment
<form id="frmA" name="frmA">
<label name="frmName">Name:</label><br />
<input form="frmA" type="text" name="frmName" id="name"/><br />
<label name="frmEmail">E-Mail:</label><br />
<input form="frmA" type="text" name="frmEmail" id="email"/><br />
<label name="age">Age:</label><br />
<input form="frmA" name="frmAge" id="age"/><br />
<label name="frmComments">Comments:</label><br />
<textarea form="frmA" cols="50" rows="10" id="comments"></textarea><br />
</form>
<button onClick="validate();">Submit</button>
i know that the checks work when no data is present however when i input data in the form and hit submit i am still faced with 4 errors. (there are 5 errors with no data: 3x presence checks, 1 for the regex and one for the isNaN)
My question therefore is why am i still getting errors and why do i get no output.
Any help would be greatly appreciated.
Extra: i would also like the input fields to change colour when there is an error.
Your regexes are wrong. You have /\s+#\s+.\s+/ and it should be /\w+#\w+\.\w+/. You didn't escape the dot and \s matches whitespace, not strings. \w matches word. For a proper email regex you would need much more than that but for your simple case to work this will suffice. The second regex should be /\w+/.

Categories