3

I have a simple application where if the user presses TAB or Space; a new input field is added to a div element.

The following is a snippet of the div element used to hold the input fields:

<div class="container" id="container" onkeydown="KeyDown(event)">
    <input type="text" maxlength="15" id="0"/>
</div>

The following is the JavaScript code I am using to add input fields:

function KeyDown(e) {
    var container = document.getElementById("container");

    if(e.which === 9 || e.which === 32) { //User pressed Tab or Space
        container.innerHTML += "<input type='text' maxlength='15' id='0'/>";
    }
}

This works, but there is a 8px margin/gap (4px more than default CSS) between the first and second text input fields. Only the first input field has an extra 4px margin, even though the CSS and HTML of the page is identical across all input fields in Chrome.

The problem is fixed by replacing the innerHTML of the container with the following Javascript:

if(c === 1) { //c is the number/count of input elements
    container.innerHTML = "<input type='text' maxlength='15' id='0'/>";
}

...
c++;

Why does this occur while adding the initial input field with HTML, versus replacing the innerHTML and them incremental each input field?

AquaGeneral
  • 155
  • 1
  • 19

2 Answers2

3

There will be whitespace between the two input tags (line break and spaces for your formatting). This will cause a single space to be rendered which will be your extra 4px. It should work if you change your initial html to:

<div class="container" id="container" onkeydown="KeyDown(event)">
    <input type="text" maxlength="15" 
    id="0"/></div>

Horrible formatting but a line break within a tag is not formatted.

I think that if you append the new input instead of manipulating the innerHTML you might also, avoid the whitespace:

function KeyDown(e) {
    var container = document.getElementById("container");

    if(e.which === 9 || e.which === 32) { //User pressed Tab or Space
        var newInput = document.createElement('input');
        newInput.id = "0";
        newInput.type = "text";
        newInput.maxlength = "15"
        container.appendChild(newInput);
    }
}

By the way, a numeric id is not valid - it should start with a letter What are valid values for the id attribute in html.

Community
  • 1
  • 1
detaylor
  • 7,112
  • 1
  • 27
  • 46
  • Thanks for the reply. I honestly had no idea that numeric values are not to be used as id's alone - good thing you pointed it out before I would have used numeric values only in the specific project. – AquaGeneral Jul 18 '11 at 10:05
1

In the first case, there're some whitespaces in the DIV.

...keydown="KeyDown(event)"> [space] [space] [cr] [lf]
[space] [space] <input type="text" max...> [space] [cr] [lf]
[space] [space] [tab] </div>

You may write:

<div ...><input ... /></div>
ern0
  • 3,074
  • 25
  • 40