krishna
krishna

Reputation: 21

Build form field names dynamically in JavaScript and assign values

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 these fields (the form field name that are dynamically build will exist in the form).

Upvotes: 0

Views: 1897

Answers (2)

user110714
user110714

Reputation:

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>

Upvotes: 2

Bryan Kyle
Bryan Kyle

Reputation: 13761

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];
   }
}

Upvotes: 0

Related Questions