Monday, May 20, 2024
192
rated 0 times [  193] [ 1]  / answers: 1 / hits: 17881  / 11 Years ago, mon, january 13, 2014, 12:00:00

Someone helped me with this earlier, but there is one problem and I already closed that question. I do not want to use JQuery. The following code works, it allows you to search a dropdown menu:



<html>
<head>
<script type=text/javascript>
function searchSel()
{
var input = document.getElementById('realtxt').value.toLowerCase(),
len = input.length,
output = document.getElementById('realitems').options;
for(var i=0; i<output.length; i++)
if (output[i].text.toLowerCase().slice(0, len) == input)
output[i].selected = true;
if (input == '')
output[0].selected = true;
}
</script>
</head>
<body>
<form>
search <input type=text id=realtxt onkeyup=searchSel()>
<select id=realitems>
<option value=>select...</option>
<option value=1>Power hungry</option>
<option value=2>Super man</option>
<option value=3>Hyperactive</option>
<option value=4>Bored</option>
<option value=5>Human</option>
</select>
</form>
</body>
</html>


Here is the problem.



It is only limited to the matching first letters of the first word. So if you typed in Super for Super Man, it would work. But if you typing with Man it will not show. Is there a way to make it match the whole string for a matching value? Thanks.


More From » drop-down-menu

 Answers
6

I have created a fiddle please check.
http://jsfiddle.net/wLzs4/3/



I have used the indexOf javascript function for your case.



function searchSel() 
{
var input = document.getElementById('realtxt').value.toLowerCase();

len = input.length;
output = document.getElementById('realitems').options;
for(var i=0; i<output.length; i++)
if (output[i].text.toLowerCase().indexOf(input) != -1 ){
output[i].selected = true;
break;
}
if (input == '')
output[0].selected = true;
}

[#73215] Saturday, January 11, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
magdalena

Total Points: 364
Total Questions: 101
Total Answers: 92

Location: Namibia
Member since Mon, Nov 14, 2022
2 Years ago
;