recursive recursion
recursive recursion

Reputation: 215

indexOf method in JavaScript

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?

Upvotes: 1

Views: 151

Answers (2)

dfsq
dfsq

Reputation: 193261

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)) {

Upvotes: 1

Adjit
Adjit

Reputation: 10305

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()

Upvotes: 2

Related Questions