0

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).

3
  • 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]; } } Commented Nov 17, 2009 at 0:19
  • the javscript function is as above Commented Nov 17, 2009 at 0:20
  • can you post the html along with your javascript and possibly your JSON object ~ a simple example is best Commented Nov 17, 2009 at 0:26

2 Answers 2

2

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

Comments

0

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

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.