Help with listbox - Problem Solved

<select id=“product_list” …

I have a list box of products (1500+),and rather than manually selecting the product from the list box, by mouse, or by typing, I want to be able to paste the product name, or partial product name, into a text box:

<input type=“text” id=“product_lookup”

In doing do, I want it to select the first item in the list box that either fully or partially matches this input.

Eg. Product List:
Widget
Blue Widget
Light Blue Widget
Dark Blue Widget

So in the above case, if I paste into the text box:
“Blue” it will select “Blue Widget”
“Dark” it will select “Dark Blue Widget”
“Light Blue” it will select “Light Blue Widget”
“Widget” it will select “Widget”
“Blue Widget” it will select “Blue Widget”
etc

Hope that makes sense.

I just cant figure out the javascript that I need to put on the onChange event for the text box to achieve this.

Thanks

You would want to use a for loop to go through the list of products, and the indexOf method, to check if the partial is found in the each item of the list.

Where a successful match is found, you then set the selected index of the list to that item, and then break out of the for loop so it doesn’t do the same for other matches in the list.

The keyup event might be more suitable.

Let’s work together :slight_smile:

The information from my post is the function that the keyup event would trigger.

Something like this perhaps? (but doesn’t work - function is called and executes just nothing ‘noticeable’ happens)


function lookup_product() {
	 var list = document.getElementById('product_list');
	 var lookup = document.getElementById('product_lookup').value;
	 
	 for(var i = 0; i < list.options.length; i++) {
		if ( list.options[i].value.indexOf(lookup) ) {
		    list.options[i].selected = true;							
		    break;
		}
	}
}


Ehh that won’t work cos the list value is numeric (product number) not the text that is display in the box.

Got it working.
If you see any problems with this, please let me know:


<script type="text/javascript"> 
	function lookup_product() {
		var list = document.getElementById('product_list');
		var lookup = document.getElementById('product_lookup').value.toLowerCase();
					 
		for(var i = 0; i < list.options.length; i++) {		
			if ( list.options[i].text.toLowerCase().indexOf(lookup) > -1 ) {
				list.options[i].selected = true;							
				break;
			}
		}
	}
</script>


Thanks for your help.

And used onKeyUp too.

Well done, it looks like you’re all set to go.