Reputation: 12213
I am trying to populate dictionary object at client side which i can pass to my Action method. I am able to build the dictionary object with hard coded values however i want to create it dynamically based on the DOM elements.
Here is the how to code looks like:
<input type="text" id="t1" class="textClass" />
<input type="text" id="t2" class="textClass" />
<input type="text" id="t3" class="textClass" />
<input type="text" id="t4" class="textClass" />
<input type="text" id="t5" class="textClass" />
<input type="button" id="btnSubmit" value="Submit" />
Here is the JavaScript function with hard coded values. I am looping thru all the text boxes that has textClass
. This works fine and i am able to see dictionary items in the Action method parameter.
<script type="text/javascript">
$('.textClass').each(function (index) {
dictionary = {
'[0].Key': 'k1',
'[0].Value': 'v1',
};
</script>
This is how i want to construct the dictionary but i am not able to figure out how do i use index and DOM element to create dictionary key and value. If i write the way i have written below, it does not construct the dictionary.
<script type="text/javascript">
$('.textClass').each(function (index) {
dictionary = {
'[' + index '].Key': $(this).attr('id'),
'[' + index '].Value': $(this).val(),
};
</script>
Can someone please point me what am i doing wrong here?
Upvotes: 0
Views: 6362
Reputation: 25145
$('.textClass').each(function(index) {
dictionary = {};
dictionary['[' + index + '].Key'] = $(this).attr('id');
dictionary['[' + index + '].Value'] = $(this).val();
});
Upvotes: 0
Reputation: 129792
To be able to construct keys from strings, you'll need to set them accordingly:
var dictionary = {};
dictionary['[' + index + '].Key'] = $(this).attr('id');
Your currently overwriting the dictionary variable for each iteration. In your scenario, you'd want something like:
var dictionary = {};
$('.textClass').each(function (index) {
dictionary['['+index+'].Key'] = $(this).attr('id');
dictionary['['+index+'].Value'] = $(this).val();
});
Upvotes: 5