leandronn
leandronn

Reputation: 170

Search input with common search values

I want to create a search input that, when I focus on it, a menu of options shows, and when I select, it can be concatenated to the search text. Example:

  |------------------------------------------------------|
  |  |                                                   |
  |  |                                                   |
  |------------------------------------------------------|

  |                                |
  |  VALUE1                        |
  |--------------------------------|
  |                                |
  |  VALUE2                        |
  |--------------------------------|

And when I click on VALUE1 my search text will be like "VALUE1:TEXT_TO_FIND".

This way, I can filter my return data easily from client side.

Thanks,

LN

Upvotes: 0

Views: 68

Answers (2)

Unnamed
Unnamed

Reputation: 1790

The Chosen jQuery Plugin might be a good option.

Upvotes: 1

ElDoRado1239
ElDoRado1239

Reputation: 4048

DEMO

<input type="text" id="field" /><br>
<select style="display:none;" id="hint" size="4">
</select>

...

var words = ["base","barrel","barbie","battle","bell","bench","breach"];
function init(){
    document.getElementById('field').onkeyup = hint;
    document.getElementById('hint').onchange = select;
}
function hint(){
    var hintElement = document.getElementById('hint');
    var fieldElement = document.getElementById('field');
    var str = fieldElement.value.substring(fieldElement.value.lastIndexOf(' ')+1);
    if(str == '')
        return;
    hintElement.innerHTML = '';
    for(var i in words)
        if(words[i].substring(0,str.length) == str)
            hintElement.innerHTML += '<option value="'+words[i]+'">'+words[i]+'</option>';
        hintElement.style.display = (hintElement.innerHTML == '') ? 'none' : '';
}
function select(){
    var fieldElement = document.getElementById('field');
    fieldElement.value = fieldElement.value.substring(0,fieldElement.value.lastIndexOf(' ')+1) +  this.value + ' ';
    this.innerHTML = '';
    this.style.display = 'none';
    document.getElementById('field').focus();
}
init();

Upvotes: 1

Related Questions