Update Input Options with Javascript

I have a Form, that looks like this:

echo $this->Form->control('deliveryradius',['type'=>'number','min'=>1,'max'=>20,'step'=>1,'value'=>$salespoint->deliveryradius,'onchange'=>"updategeonames(this.value)"]);
<div id="geonames">
       echo $this->Form->control('geonames._ids',[
        'options'=>$geonames->map(function($geoname,$key) {
           return [
                 'text'=>$geoname->country.' '.$geoname->postalcode.' '.$geoname->placeName.__(' calculated Distance: ').$this->Number->precision($geoname->distance,2).' km'

The Javascript:

function updategeonames(val) {
    var csrfToken = <?= json_encode($this->request->getAttribute('csrfToken')) ?>;
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
      if (this.readyState==4 && this.status==200) {
    xmlhttp.open("GET","<?php echo $this->Url->build(['controller'=>'Salespoints','action'=>'updategeonames?q=']); ?>"+val,true);
    xmlhttp.setRequestHeader('X-CSRF-Token', csrfToken);

On changing the value of


a request is sent to the controller. (I checked it with a simple debug).

What I like to know, is how to get the updated variables $geonames and $selectedgeonames into my select input field.

In Salespoints/updategeonames set the ajax template

function updategeonames()
    $options = // ...... find('list')
    $selected = // ..... asuming array of IDs
    $this->set(compact('options', 'selected');

on your template:

<?php foreach ($options as $id => $name): ?>
<?php $isSelected = in_array($id, $selected) ? 'selected' : ''; ?>
  <option <?= $isSelected ?> value="<?= $id ?>">
     <?= h($name) ?>
<?php endforeach; ?>

that should work if you are replacing the innerHTML of the select

1 Like

@raul338 Thanks for your help. Your advice brought me on the right way.

I am trying to create a select input where a user can search for select options and the drop down would dynamically change.

For instance, there is an Opinion model. A user can share there opinions about different movies. I have a different Movies table. So, the form for creating an Opinion https://snaptube.cam/ will have an a select input field for Movies . Where user can search the movies with name and then select it.

Can you guys please help me with this?

There’s any number of tutorials out there about how to do this sort of autocomplete. Is there a particular piece you’re struggling with, or just don’t know where to even start?