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

yossi
  • 3,090
  • 7
  • 45
  • 65

1 Answers1

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758