开发者

Build form field names dynamically in JavaScript and assign values

开发者 https://www.devze.com 2022-12-12 04:09 出处:网络
The code: function updateValues(res){ var rows=res.ROWCOUNT; for (i=0;i<rows;i++){ var x=\'document.Eventform.txt_\'+res.DATA.EVENT_LENDER_ID[i];

The code:

function updateValues(res){
                var rows=res.ROWCOUNT;
                for (i=0;i<rows;i++){
                    var x='document.Eventform.txt_'+res.DATA.EVENT_LENDER_ID[i];
                    x.value=res.DATA.EVENT_DAYS[i];
                }
            }

res is a JSON object passed to the function and we need to dynamically build form fields names and assign values to thes开发者_Go百科e fields (the form field name that are dynamically build will exist in the form).


If you want to create a form dynamically from javascript you can do it like this...

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>JS Example</title>
</head>
<body>

    <div id="formContainerDiv">

    </div>

    <script type="text/javascript">

        var form = document.createElement('form');

        for (var i = 0; i < 10; i++) {

            var element = document.createElement('input');

            element.type = 'text';
            element.value = i.toString();

            form.appendChild(element);
        }

        var submit = document.createElement('input');

        submit.type = 'submit';
        submit.value = 'submit';

        form.appendChild(submit);

        document.getElementById('formContainerDiv').appendChild(form);

    </script>
</body>
</html>


The following code should do what you want

function updateValues(res) {
   var rows = res.ROWCOUNT;
   var form = document.forms['EventForm'];

   for (var i=0; i<rows; i++) {
      form.elements['txt_' + res.DATA.EVENT_LENDER_ID[i]].value = res.DATA.EVENT_DAYS[i];
   }
}

However, if you can change the layout of the JSON object to something else you might be able to make that code a little bit cleaner:

function updateValues(res) {
   var form = document.forms['EventForm'];
   for (var name in res) {
      form.elements['txt_' + name].value = res[name];
   }
}

Even better would be if the form fields had their id attribute set to the name contained in the JSON object. In that case the following would work (in conjunction with changing the JSON object):

function updateValues(res) {
   for (name in res) {
      document.getElementById(name).value = res[name];
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消