Philip007
Philip007

Reputation: 3230

JQuery syntax error when selecting element of the same name

I want to select input with the same name, but get syntax error:

$("input[name=$(this).prop('name')]"); 

But I am able to get string by $(this).prop('name').

EDIT:

Thank you for all your answers. I think they all work. But could anyone explain why the two plus sign at beginning and end make the jquery code parsed inside string? Reference will be appreciated, thanks

EDIT2:

I know plus sign is for string concatenation. But in this case, nothing is before the first + or after second +. So what are being concatenated here? Sorry if the question looks too naive

Upvotes: 1

Views: 73

Answers (4)

orlenko
orlenko

Reputation: 1271

But could anyone explain why the two plus sign at beginning and end make the jquery code parsed inside string?

Let's look at it step by step.

First, let's take the original approach:

$("input[name=$(this).prop('name')]"); 

The function "$" (which is an alias for jQuery) will get called with a string argument:

"input[name=$(this).prop('name')]"

jQuery will parse this string and interpret it like this:

/* 
Okay, I need to find an <input> 
that has an attribute "name", 
and the value of that attribute has to be, literally, "$(this).prop('name')". 
So, I'm looking for something that looks like this: */

<input name="$(this).prop('name')" />

However, what you probably meant to find was more like this:

<input name="some name, actually" />

(and "some name, actually" would be in the name property of $this at the point where you are making the original call)

Let's look at the new approach now:

When you write

$("input[name=" + $(this).prop('name') + "]");

You are constructing part of the string from your JavaScript objects. You are taking $(this) (which is a jQuery object), call its function "prop" to retrieve a property called "name", and using the output of that function in the new query. So if $(this).prop('name') returns "AWESOME", you are asking jQuery to find something that looks like this:

<input name="AWESOME" />

This should be more like what you were looking for!

Upvotes: 3

Alessandro Dias
Alessandro Dias

Reputation: 77

Try something like this:

$("input[name=" + $(this).prop('name') + "]");

Upvotes: 2

Joey
Joey

Reputation: 1679

You're literally looking for an input element with the name $(this).prop('name'). What you want to do is write something like this:

$("input[name="+$(this).prop('name')+"]"); 

Upvotes: 2

JCOC611
JCOC611

Reputation: 19729

It should be this:

$("input[name='"+$(this).prop('name')+"']"); 

jQuery doesn't parse jQuery code on strings. For it to be executed you should place the jQuery prop() function outside the string.

Upvotes: 4

Related Questions