Jump to main content

Datalist

We can use the HTML datalist element to attach suggestions to an input box; like names, events, products or frequent search terms. Sometimes referred to as a 'typeahead'. These suggested terms make input box entries quicker, easier and less error-prone for the website user. The example here demonstrates how the datalist options could be edited using WebYep, for the benefit of clients wanting complete control over the list of options shown. Edit mode presents a loop with suggested terms neatly organised as a list.

Example

HTML & PHP


<form action="https://en.wikipedia.org/w/index.php" method="get" target="_blank" class="search_form">
  <input type="search" name="search" autocomplete="off" list="code-languages">
  <input type="submit" value="Search">
</form>


<?php if(webyep_bIsEditMode() == false) : ?><datalist id="code-languages"><?php endif; ?>
<?php if(webyep_bIsEditMode() == true) : ?><ul class="edit_mode_list"><?php endif; ?>
<?php foreach ((new WYLoopElement())->aLoopIDs("Search Box Options") as $webyep_oCurrentLoop->iLoopID) { $loopid=$webyep_oCurrentLoop->iLoopID; $_SESSION["loopid"]=$loopid; $webyep_oCurrentLoop->loopStart(true,$webyep_oCurrentLoop->iLoopID); // WebYepV2 ?>
  <?php if(webyep_bIsEditMode() == true) : ?><li>
  <?php if(webyep_bIsEditMode() == false) : ?><option value="<?php endif; ?><?php if(webyep_bIsEditMode() == false) : ?>"><?php endif; ?>
  <?php if(webyep_bIsEditMode() == true) : ?></li><?php endif; ?>
  <?php $webyep_oCurrentLoop->loopEnd(); } unset($_SESSION["loopid"]); // WebYepV2 ?>
<?php if(webyep_bIsEditMode() == true) : ?></ul><?php endif; ?>
<?php if(webyep_bIsEditMode() == false) : ?></datalist><?php endif; ?>

CSS

.search_form {
  display: flex;
}

.search_form input[type="search"],
.search_form input[type="submit"] {
  padding: 0.75rem;
  transition: 200ms;
  font-size: 1.2rem;
  border-radius: 0.5rem;
}

.search_form input[type="search"] {
  border: 2px solid #ccc;
  flex: 1;
  outline: none;
}

.search_form input[type="search"]:focus {
  border: 2px solid hsl(280, 70%, 50%);
}

.search_form input[type="submit"] {
  margin-left: 0.5rem;
  border: none;
  background: hsl(280, 70%, 50%);
  color: white;
}

.search_form input[type="submit"]:hover {
  background: hsl(280, 70%, 30%);
}

/* Styling applied to our list of options in edit mode only */
ul.edit_mode_list {
  list-style: none;
  padding: 0;
  margin: 0;
}

ul.edit_mode_list li {
  background: hsl(280, 70%, 90%);
  padding: 0.25rem;
}

Javascript