views:

29

answers:

3

I'm trying to iterate through a complex type binding in jQuery to submit the Json representation through to an IEnumerable action parameter.

Html

<input type="hidden" value="0" name="value.index" />
<input type="text" value="textone" name="value[0].InputValue" id="value[0].InputValue" />
<input type="hidden" value="0" name="value[0].Id" id="value[0].Id" />

jQuery

var value = $('#value[0].InputValue').val()

The value returned is undefined; however if I have a control with an id in the format of "myId" then I can access the value of that control.

Am I missing something? Or is this not possible?

+2  A: 

# is used to find the element by Id. If you want to find the element by Name, it follows a different syntax... Try this

$("input[name=value\[0\].InputValue]");
Teja Kantamneni
Ah, forgot to escape the []'s - good catch Teja :)
Dan
Ta muchly, this was what I was looking for :-)
WestDiscGolf
+1  A: 

I don't think []'s are allowed in IDs. MVC replaces them with underscores when I render a textbox with a name of Obj[0].Property

I'd try getting the input by the name:

EDIT - escape the brackets :)

$('input[name=value\[0\].InputValue]').val()

You can do a variety of attribute selectors too:

http://api.jquery.com/category/selectors/

Hope that Helps!

Dan
Ta, brilliant! :-)
WestDiscGolf
A: 

This problem arises because the [ and ] characters mean special things in a jQuery selector, namely they specify requirements on attributes. so when you say

$('#value[0].InputValue')

that means to jQuery "element with id of "value" and the attribute "0" present and with the css class InputValue applied.

As others have suggested, use $('input[name=value[0].InputValue')` instead.

Tomas Lycken