bhawin bhawin - 5 months ago 14
CSS Question

place a div just below a textbox

i have searched a lot but didn't got any result which is satisfying
i am trying to get a div just below a text using javascript for my autocomplete textbox

<input type="text" id="one" onkeyup="suggest(event,this)" />
<p>
<input type="text" id="two" onkeyup="suggest(event,this)" />
<p>
<input type="text" id="two" onkeyup="suggest(event,this)" />

javascript:
function suggest(e,the)
{
//here i want to create a div and place just below the textbox on which the keyispressed
}

any help!

Answer

In general it is not a good idea to attach javascript events into the html. My idea is to dynamically create a div and position it just below the input field I think that the following code will work. Here is also a jsfiddle http://jsfiddle.net/krasimir/qCXPu/3/

<div class="wrapper">
<input type="text" id="one" class="suggest" />
<p>some text</p>
<input type="text" id="two" class="suggest" />
<p>some text</p>
<input type="text" id="three" class="suggest" />
</div>

JavaScript:

var inputs = document.querySelectorAll('.suggest');
for(var i=0; field=inputs[i]; i++) {
    field.addEventListener('keyup', function(event) {
        var text = 'You typed: ' + this.value;

        if(!this.suggestion) {
            var rect = this.getBoundingClientRect();
            var left = rect.left;
            var top = rect.bottom;
            this.suggestion = document.createElement('DIV');            
            this.suggestion.innerHTML = text;
            this.suggestion.setAttribute('style', 'background: #B0B0B0; padding: 6px; position: absolute; top: ' + top + 'px; left: ' + left + 'px;');
            this.parentNode.appendChild(this.suggestion);
        } else {
            this.suggestion.innerHTML = text;
            this.suggestion.style.display = 'block';
        }        

    });
    field.addEventListener('blur', function(event) {
        if(this.suggestion) {
            this.suggestion.style.display = 'none';
        }
    });
}
Comments