1

I've toyed with this for the last hour and am finally asking for some advice/help on what's causing this issue. I'm creating a small fallback using RegEx, the first input works fine, but the second returns undefined. Here's the HTML:

<input type="email" value="[email protected]" />
<input type="text" pattern="[A-Za-z]{3}" value="ABC" />

You'll see from the jsFiddle and Console that it prints 'Success' for the type="email" input, but returns undefined for the pattern fallback. I basically want to reuse the same function and pass the parameters into it and get the value returned dynamically.

I have a feeling this might be the issue line:

var patternFallback = $(this).attr('pattern')

... Perhaps it somehow needs 'converting' for the JS to read it as RegEx?

Here's my jsFiddle if you can help, and thank you! The script is a section of the full code, which includes the problem area, the loop through elements and the variables I'm passing through the function: http://jsfiddle.net/fTk7e/

Many thanks in advance.

2
  • 3
    You have $(this).attr('pattern') outside of any sort of event handler. Therefore this is not your element. Commented Jun 11, 2013 at 20:03
  • Ah yes sorry, that's meant to be inside the loop. However, the answer below is what I needed. Commented Jun 11, 2013 at 20:07

3 Answers 3

2
var patternFallback = $(this).attr('pattern')

The value of 'this' where you are calling the function is a reference to the document object. You need to move this variable definition inside your each() call. This is why you're getting undefined.

And you should be creating a regular expression out of the string. You can't call .test() on a string.

var patternFallback = RegExp($(this).attr('pattern'));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks nderscore, slight type 'RexExp' though! :)
1
new RegExp($(this).attr('pattern'));

Comments

0

I agree with Rocket Hazman. Give the inputs an ID and test it that way.

<input id="myEmailId" type="email" value="[email protected]" />
<input id="myTextId" type="text" pattern="[A-Za-z]{3}" value="ABC" />

And in javascript:

var patternFallback = $("#myTextId").attr('pattern');

1 Comment

Thanks Erik. I had meant to include the $(this) within the $.each loop, and what I needed was the new RegExp($(this).attr('pattern'));

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.