0

I have a jQuery function that receives id of div element and json array

function FormBuilder(selector,myList){
    for (var i = 0 ; i < myList.length ; i++) {
        var rowHash = myList[i];
        if(rowHash['id'] > 0 ){
            $(selector).append('<form id="DialerInfo">');
            for (var key in rowHash) {
                $(selector).append(key +': <input type="text" name="' + key + '" value="' + rowHash[key] + '"><br/>');
            }
            $(selector).append('</form>');
        }
    }
}

And I expected this to build a proper form, i.e. all inputs should be between <form> and </form> tags. But I'm receiving something completely different:
First goes
<form id="DialerInfo"></form> then below all input fields. Why are they outside the form tags? does jQuery close all tags automatically? how to prevent this behavior then?

2 Answers 2

3

DOM creation using jQuery doesn't work like string concatenation

You can create a form and append all the elements to it

function FormBuilder(selector, myList) {
  var $form = $('<form id="DialerInfo"></form>').appendTo(selector);
  for (var i = 0; i < myList.length; i++) {
    var rowHash = myList[i];
    if (rowHash['id'] > 0) {
      for (var key in rowHash) {
        $form.append(key + ': <input type="text" name="' + key + '" value="' + rowHash[key] + '"><br/>');
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

//use

$.each(arrayorJSON,function(KEY,VALUE){
    //YOUR CODE HERE
}) 

//it is a jquery looper which accepts both array and json values and compatible with all browsers instead of for loop

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.