0

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?

2 Answers 2

5

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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I had it hardcoded to see if it works or not. Your answer works great. Thanks again.
0
$('.textClass').each(function(index) {

    dictionary = {};
    dictionary['[' + index + '].Key'] = $(this).attr('id');
    dictionary['[' + index + '].Value'] = $(this).val();

});

Comments

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.