2

I am using php & javascript. I have written the code for dropdown menu. Now I want to write a code where I enter word in the textbox & it will suggest the word from the dropdown. Like if I enter 'abc' in text box , it will give all the result start with 'abc' from the drop down. Please provide me proper code in php or javascript... that will fulfill my conditions. Thank you. below is a dropdown code. I want search & suggest code.

<label>Site Name:</label>
<select id="combobox">
 <option value=""></option>
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="fiat">Fiat</option>
 <option value="audi">Audi</option>
</select>   
<input type="submit" name="submit" value="submit"/> 
sharvanaz
  • 75
  • 1
  • 2
  • 10

1 Answers1

2

Maybe the datalist element could help

<form action="action_page.php">
   <input list="browsers">
   <datalist id="browsers">
     <option value="Internet Explorer">
     <option value="Firefox">
     <option value="Chrome">
     <option value="Opera">
     <option value="Safari">
   </datalist> 
</form>

Taken from: http://www.w3schools.com/html/html_form_elements.asp

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

Edit:

And if you just want a javascript-solution: Add:

<input type="text" id="search" onkeyup="change()" />

and

var e = document.getElementById("combobox");
var t = document.getElementById("search");
function change() {
    var ts = t.value.toLowerCase();
    if (ts.length < 1) {
        e.selectedIndex = 0;
        return;
    }
    for (var i = 0; i < e.options.length; i++) {
        var es = e.options[i].text.toLowerCase();
        if (es.lastIndexOf(ts, 0) === 0) {
            e.selectedIndex = e.options[i].index;
            return;
        }
    }
    e.selectedIndex = 0;
}
Community
  • 1
  • 1
Andre
  • 385
  • 1
  • 13
  • You gave me the code of dropdown. I do not have any problem with the code of dropdown. I want a code that will search & suggest the word from the dropdown list. – sharvanaz May 10 '16 at 10:40
  • 1
    @Andre, nice answer. +1. Please ensure that Reference link of w3schools is not authenticated. Use https://www.w3.org/ OR https://developer.mozilla.org/en-US/ OR https://msdn.microsoft.com/en-us/default.aspx. – Pupil May 10 '16 at 10:44
  • This code does exactly that. It searches and suggests the words from the datalist... which will also work as a dropdown list – Andre May 10 '16 at 11:37