-2

I am trying to use JavaScript to find the contents of an input. I have tried this:

var x = document.getElementById("inputID");
 function myFunction() {
  if (x.value == 'Hi') {
     alert('Hello')
  } else {
    alert('Goodbye')
  }
 }

But it will not work. Please help!

msarchet
  • 15,104
  • 2
  • 43
  • 66

1 Answers1

2

Corrected Version

var inputEl = document.getElementById("inputID");

unction myFunction() {
  if (inputEl.value === 'Hi') {
    alert("Hello");
  } else {
    alert("Goodbye");
  }
}

Which is pretty much what you had, except for few fixes and best practices:

  • the variable name change (inputEl instead of 1 - see Valid Identifiers below)
  • the strings in the alert statements (maybe they were variables, but we couldn't assert it from your snippet);
  • the strict equality comparison;
  • the missing semi-colons;

Why It Didn't Work

It doesn't work because of the 1 variable name being invalid.

Then if it still doesn't work after that, then your HTML is wrong and the ID of your element isn't really inputID,

Valid Identifiers

if you try this in Chrome's console (or another JS environment) to replicate your variable declaration:

var 1 = 'test';

You'll get a nice output similar to:

SyntaxError: Unexpected number

So, just changing your variable name should be enough, if there aren't any other issues.

FYI, According to the Mozilla Developer Network, valid identifiers in JavaScript are:

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the \uXXXX Unicode escape sequences as characters in identifiers.

For a less digestable version, the full spec for identifiers is in the 5.1 Edition of the ECMA-262 standard in section 7.6

haylem
  • 22,460
  • 3
  • 67
  • 96
  • I didn't originally have variables called "1". I changed the names because they were very long and complicated. –  Aug 10 '14 at 16:50
  • @PrOdIgYCaRcAsS: then most likely your HTML didn't match your Javascript. Give us the full code and we can help further. – haylem Aug 11 '14 at 10:56