How to select value on focus for a selectize?

I want to select value on focus for selectize.

At this moment, I can just click and remove the value, but I want click(focus) should select all value strings of selectize element.

You could see how Google calendar works while creating new event.

enter image description here

On my side, if I click the time selectize element, then it should select all value strings and the selection can be removed or updated with new strings like Google.

enter image description here

My time selectize element is the following.

// php
<div class="select-beast is-hide-selectize-arrow select-event-time-end">
    <select name='event_time_end' class='control is-normal select-time' required>
         <?php echo TimeHelper::get_times(); ?>
    </select>
</div>

// php
function get_times ($default = '19:00', $interval = '+30 minutes') {

    $output = '';

    $current = strtotime('00:00');
    $end = strtotime('23:59');

    while ($current <= $end) {
        $time = date('H:i', $current);
        $sel = ($time == $default) ? ' selected' : '';

        $output .= "<option value="{$time}"{$sel}>" . date('h:i A', $current) .'</option>';
        $current = strtotime($interval, $current);
    }

    return $output;
}

...
//jquery
<script>
    const $selected_time_start = $('.select-beast select[name="event_time_start"]').selectize({
         create: true
    });

    const selectize_event_start = $selected_time_start[0].selectize;
</script>

What I tried is to use focus event and select method like the following. But it didn’t work.

$('.select-beast select[name="event_time_start"]').focus(function() { $(this).select(); } );

Answer

After research over 3 hours, I’ve found the most relative answer.

I need to update the selectize version to the latest and use select_on_focus plugin.

The plugin is here. https://github.com/selectize/selectize.js/tree/master/src/plugins/select_on_focus

How to use:

If you are using jQuery, you can use standalone version of selectize.

...
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/js/standalone/selectize.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/css/selectize.min.css" rel="stylesheet">
</head>
<body>
  ...
  <select class="selectize"></select>
  ...
</body>
<script>
  const $selectize = $('.selectize').selectize({
    options: options,
    plugins: ['select_on_focus'],
    ...
  });
</script>

You see how to import the plugin, right?

Leave a Reply

Your email address will not be published. Required fields are marked *