2

I'd like to get an input name, as a property name, using jquery.

The html

<input name="data[First][Second]" />

The script

$.post(
   '/url', 
   {
      $("input").prop("name"): $("input").val()
   }
);

how can it be done (directly)?

1
  • 2
    It can't. You have to do it in two steps. Commented Sep 9, 2014 at 7:59

1 Answer 1

2

You can't use a variable value as a property name in a literal. You have to do it in two steps and to use the bracket notation :

var obj = {};
obj[$("input").prop("name")] = $("input").val();
$.post('/url', obj);

If you don't want to break the flow and you want an expression, you can use a function expression :

$.post(
   '/url', (function(){
       var obj = {};
       obj[$("input").prop("name")] = $("input").val();
       return obj;
    })()
);

A very slight advantage is also that you don't pollute the external scope with a new variable, but it's usually not clearer.

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

3 Comments

I'm sure it's a duplicate, I've seen it, but I can't find it :\
@yossi You might be interested in this article : benalman.com/news/2010/11/…

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.