yossi
yossi

Reputation: 3164

Jquery & javascript - function result, as property name

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

Upvotes: 2

Views: 43

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382274

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.

Upvotes: 2

Related Questions