1

I'm new to javascript. I am trying to add multiple text box dynamically on run time..

        <script type="text/javascript">
            function ajax(){
                var x = document.getElementById("ajax").innerHTML;
                x= x + '<input name="reference[]" type="text" />';
                document.getElementById("ajax").innerHTML = x;
            }
        </script>

This is an on click event. Here my problem is that every time add a new text box the value of my previous text box disappears and an all the text boxes are empty each time the function is called.

1
  • Despite the minimal attempt of HTML5 to standardise innerHTML, it is inconsistent across browsers, especially regarding attributes and properties. Do not rely on it for non-trivial purposes. Commented Oct 11, 2011 at 10:44

2 Answers 2

2

I would suggest using document.createElement and document.appendChild

Example

function ajax() {
    var textBox = document.createElement('input');
    textBox.name = 'reference[]';
    textBox.type = 'text';
    document.getElementById("ajax").appendChild(textBox);
}
Sign up to request clarification or add additional context in comments.

1 Comment

yeah thats the right way to add elements to page... not to append some html text string
0

Append to existing content not overwriting it

Append:

document.getElementById("ajax").innerHTML += x;

Overwrite

document.getElementById("ajax").innerHTML = x;

Use this

<script type="text/javascript">
            function ajax(){
                var x = '<input name="reference[]" type="text" />';
                document.getElementById("ajax").innerHTML += x;
            }
</script>

3 Comments

DOM does not recommend same name for two elements. But using JQuery, (change reference[] to reference) u can get the values with selector $("#reference"). If you want these values on server side, which language you are using?
@hungryMind - there is nothing wrong with giving multiple elements the same name where it is specified as an attribute in the HTML standard. Please provide a reference where "DOM" says otherwise.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.