简体   繁体   中英

How to limit user input in a datalist?

I'm trying to make a webpage that contains a list of flights which can be filtered by destination, origin, price, etc. To do this, I've put each flight into a div with its properties as its classes. For example, a flight with its destination as America, its departure time at 2:40pm, and a price of $300 would be notated as

<div class = flight America 240PM 300> *Insert descriptive text here* </div>

However, I realized that by doing it this way, a person would be able to filter the flights by placing "America" in the price input section, as there's no way to differentiate between the price class and the destination class. Thus, I wanted to know how to limit the user's input in each input section. I've been attempting to implement this using a datalist with freeform text still available so the user won't have to scroll down endlessly in order to the find the specific airline or destination they want to filter by, but this allows them to input entirely custom filters (as seen in https://jsfiddle.net/5mwo6agb/3/ ). How do I limit the user input to only the choices available in the datalist, while still allowing them to type in the textbox in order to filter their choices?

(Also, if the way I'm going about this is entirely wrong, feel free to inform me as I'm still a pretty big newbie to javascript and html).

Ciao, you could use onchange event on input to verify that the user insert a value that is contained in your options in this way:

<input type="text" list = "combo-airlines" id="airline" placeholder="Select an Airline" name = "airline" style = "font-size:20px;" onchange="get_data(this)"/>

Then the get_data function will be:

get_data = function(elem) {
  var options = document.getElementById('combo-airlines').getElementsByTagName('option');
  var optionVals = [],
    i = 0;

  for (i; i < options.length; i += 1) {
    optionVals.push(options[i].value);
  }

  if (optionVals.indexOf(elem.value) > -1) {
    console.log(elem.value);
  }
  else {
    console.log("wrong answer")
  }
}

Here your fiddle modified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM