dynamic dictionary using javascript

醉酒当歌 提交于 2019-12-12 05:47:39

问题


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?


回答1:


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();
});



回答2:


$('.textClass').each(function(index) {

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

});


来源:https://stackoverflow.com/questions/12489935/dynamic-dictionary-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!