1

So I have the line

var a = document.cardform.cardnumber.value.toString;

Then later:

else if (a.indexOf(' ')!=0 ||a.indexOf('+')!=0 || a.indexOf('-')!=0){

This checks that the user hasn't entered any unwanted +'s, -'s, or ' 's. The line seems to raise an error that looks like this:

Uncaught TypeError: undefined is not a function.

I'm confused as to what it's telling me. Is it saying undefined isn't a function, or that 'a' is an incompatible data type? How do I fix this problem?

4
  • 2
    It's telling you that the function String.prototype.toString doesn't have an indexOf property. Commented Mar 10, 2015 at 22:19
  • 2
    toString is a function, but in any case, value is already a string. Commented Mar 10, 2015 at 22:19
  • Also, you probably want to check whether indexOf returns -1. It will return 0 if that character is the first character in the string (assuming you actually call toString first). Commented Mar 10, 2015 at 22:20
  • The built-in (on modern browsers) trim method on strings may be of more use. var a = document.cardForm.cardnumber.value.trim(); Commented Mar 10, 2015 at 22:21

2 Answers 2

2

You need to actually call the toString() function.

var a = document.cardform.cardnumber.value.toString();

Now, a is a string and has the method .indexOf()

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I feel stupid now, spent 30 minutes and all it was was a set of parentheses...
No problem, but as others noted, when getting the value of an input field you don't need to call the toString() function.
1

If you really want to use toString method, then you need to call it, otherwise a is a function which doesn't have any indexOf method.

But you don't really need to do this, because document.cardform.cardnumber.value is already a string. Remember that form elements values are always strings.

Finally you can make a check much simpler with a basic regular expression:

else if (/[-+\s]/.test(a)) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.