0

I am trying to dynamically create a key in a JavaScript object with a jQuery selector:

{
  $("form").children("input[type=hidden]").attr("name"): $("form").children("input[type=hidden]").val()
}

This is breaking though. Is it possible to dynamically create a key this way?

3
  • Do you only have one input element, or should it work for multiple values? Commented Jan 22, 2013 at 9:36
  • Only a single hidden input. Commented Jan 22, 2013 at 9:37
  • 1
    I wouldn't recommend having a input[type=hidden] selector; if you add another hidden input value, it might break your code. It would be better if you named it. Commented Jan 22, 2013 at 9:38

2 Answers 2

3

You can do it in two statements :

var obj = {};
obj[$("form").children("input[type=hidden]").attr("name")]
    = $("form").children("input[type=hidden]").val();

I'd personally write it like this to avoid recreating the jQuery set:

var obj = {}, $obj = $("form").children("input[type=hidden]");
obj[$obj.attr("name")] = $obj.val();

Note also that this only makes sense if the jQuery set contains exactly one element.

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

Comments

1

You can also make it work with multiple fields at once:

var obj = {};
$('form > input[type="hidden"]').each(function (i, el) {
    obj[el.name] = el.value;
});

Another more fancy version in case if you have only one hidden field:

var obj = $('form > input[type="hidden"]').serializeArray()[0];

4 Comments

Not bad but OP commented to say he only has one field.
Oh, right, didn't see that. Anyway, maybe someone will need it.
Yes, you should keep your answer, this might be useful ;)
But note that your selector isn't equivalent to what OP gave. You probably should add > (supposing OP had a good reason to use children).

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.