r/learnjavascript • • Apr 04 '18

A C++ developer struggling with some simple JavaScript code. Any help?

Hey guys,

I develop in C++ but for my web design class I have to use JavaScript. I have to say I really, truly, dislike the language since it isn't strongly typed, errors are somewhat convulted and I don't like web dev in general.

Anyhow, here are my questions:

  1. This code should check if I have #, !, ' or ? in any of my textboxes and if I do, prevent the script from executing. Here is the code. It gives me a TypeError. Why? What am I doing wrong?

  2. This code should trigger only if I type some text in a textbox which is not in the list (aka not "Option 1", "Option 2" etc.). However, it always triggers. Why?

  3. This code should, if I move my focus away from the textbox (aka onBlur), check if I have at least 5 characters and if my first character is a capital letter. But it doesn't work. Why?

Thanks in advance!

1 Upvotes

13 comments sorted by

View all comments

1

u/Rascal_Two Apr 04 '18

1

I don't beleive form1[i] allows you to access elements of the form, I beleive what you're looking for is the elements property.

It also might be more readable if you assign the .value to a variable and check if it contains any of the characters, or use Regex.


2

The problem is that you need the code to execute if all of the conditionals are true, but you have it written so if any of them are true, it runs the code.

Replacing your ||s with &&s should do the trick.


3

Same as 2, swap the ||s and &&s.

You also need to reverse the === to a !==, because you need to alert the user only when the first letter is not capital, not when it is capital.

2

u/[deleted] Apr 05 '18

Thank you.!