streetlight
streetlight

Reputation: 5968

Passing String as parameter into jQuery function

I'm having a strange jQuery issue. I'm writing a function that accepts a string as a parameter, and then am feeding that string into a jQuery selector.

Here is the function:

function myFunction(specialfields) {
   if(!$(specialfields).is(':focus')) {
       alert('thats not in focus');
   }
 }

However, I keep getting this error:

 Uncaught Syntax error, unrecognized expression: focus 

What's strange though is that the '.is(':focus') ' works in other areas, when not accepting a parameter, and if I pass this:

 $(specialfields)

It does read as valid object. I am trying to pass a string like this:

#id1, #id2

In addition, this works:

$(specialfields).val()

Anyone have any idea whats going here?

Upvotes: 0

Views: 8781

Answers (3)

Jeromy French
Jeromy French

Reputation: 12121

Conclusion

Your way worked all along and works faster than my waste-of-time alternative.


Detail

I defined the function a little differently, and I replaced the alert() functionality by passing the response to a <p id="response">.

HTML:

<input type="text" name="id1" id="id1" />
<br />
<input type="text" name="id2" id="id2" />
<br />
<p id="response">response</p>

JavaScript:

var myFunction = function (specialfields) {
  if ($(specialfields + ':focus').length === 0) {
    $('#response').text(specialfields + ' is not in focus');
  } else {
    $('#response').text(specialfields + ' is in focus');
  }
};

See http://jsfiddle.net/jhfrench/UufWD/ for a working example.

You'll notice I evaluate the passed-in parameter for :focus with if ($(specialfields + ':focus').length === 0).

I thought this would be faster, but that is not the case.

On the plus side, this method does handle multiple selector arguments (such as #id1, #id2'); see http://jsfiddle.net/jhfrench/UufWD/19/). But your original evaluation of if(!$(specialfields).is(':focus')) is better.


Now see http://jsfiddle.net/jhfrench/UufWD/14/ for a working example of your approach.

Upvotes: 1

streetlight
streetlight

Reputation: 5968

Okay, I believe the issue was the fact I was passing two parameters into "specialfields", which broke the ':focus' selector as obviously you can't have two fields in focus at the same time.

It can be fixed by passing just a single selector in the function.

Upvotes: 1

SaK
SaK

Reputation: 420

I think .focus() should be enough, as :focus is not a selector.

There is no native solution but yes there is a more elegant way you can do it:

jQuery.extend(jQuery.expr[':'], {
  focus: "a == document.activeElement"
});

You're defining a new selector. See Plugins/Authoring. Then you can do:

if ($("...").is(":focus")) {
  ...
}

Source-- Is there a 'has focus' in JavaScript (or jQuery)?

Upvotes: 0

Related Questions