Demo - ComboBox

by Joel Parks

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.grapecity.com/wijmo/5.latest/styles/wijmo.min.css">
<script src="https://cdn.grapecity.com/wijmo/5.latest/controls/wijmo.min.js"></script>
<script src="https://cdn.grapecity.com/wijmo/5.latest/controls/wijmo.input.min.js"></script>
<div class="container">

  <h1>
    ComboBox
  </h1>
	<p>This sample shows how to updated the dropdown based on the 'selected text' in the ComboBox.</p>
  <p>After typing in 2 characters, the ComboBox itemsSource will be trimmed down so that the only values showing are the ones that end with the selected text within the ComboBox text field.</p>
	<label for="theComboString">Strings:</label>
  <div id="theComboString"></div>
</div>

CSS

.wj-combobox {
  margin-bottom: 12px;
}

body {
  margin-bottom: 24px;
}

JavaScript

onload = function() {

  // create some random data
  var countries = 'China,Germany,Greece,Italy,Japan,Portugal,Prussia,Russia,Spain,UK,US'.split(','),
    data = [];
  for (var i = 0; i < countries.length; i++) {
    data.push({
      country: countries[i],
      active: i % 5 != 0,
      sales: Math.random() * 100000,
      expenses: Math.random() * 50000
    });
  }

  // select a country (string)
  var theComboString = new wijmo.input.ComboBox('#theComboString', {
    /*selectedIndexChanged: function(s, e) {
    	setText('theComboStringCurrent', s.text);
    },*/
    itemsSource: countries,
		/*textChanged: function(s, e) {
			let text = s.text;
			let enteredText = s.text.slice(0, s.inputElement.selectionStart);
			let highlightText = s.text.slice(s.inputElement.selectionStart);
			if(enteredText.length >= 2) {
				console.log('Calling trimItemsSource...');
				trimItemsSource(s, highlightText);
			}
		}*/
	});
	
	theComboString.hostElement.addEventListener('keydown', function (e) {
		let text = theComboString.text;
		let enteredText = theComboString.text.slice(0, theComboString.inputElement.selectionStart);
		let highlightText = theComboString.text.slice(theComboString.inputElement.selectionStart);
		if(enteredText.length > 1) {
			trimItemsSource(theComboString, highlightText);
		}
	});

	// show text in an element on the page
  function setText(id, value) {
  	document.getElementById(id).textContent = value;
  }
	
	function trimItemsSource(comboBox, trimValue) {
		var updatedItemsSource = [];
		let trimValueLength = trimValue.length;
		let comboLength = comboBox.itemsSource.length;
		for(i = 0; i < comboLength; i++) {
			var currentListItem = comboBox.itemsSource[i];
			var listItemTrimmed = currentListItem.slice(currentListItem.length - trimValueLength);
			if(listItemTrimmed === trimValue){
				updatedItemsSource.push(currentListItem);
			}
		}
		comboBox.itemsSource = updatedItemsSource;
		comboBox.refresh();
	}
}