How to set default value in materialize autocomplete input?

Jass

I am using ASP .NET MVC for my web application. I am using materialize theme (css and js) for UI. I want autocomplete input and with materialize syntax it,s working perfectly. But I want to select first option on load(using code) and I couldn't find any reference for that. Here's my code.

HTML

            <div class="input-field col s12">
                <label for="autocompleteInput">Chainage Number</label>
                <input type="text" id="autocompleteInput">
            </div>

JS:

  $(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "/Vids/GetChainageNoList",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            $.each(response, function (index, item) {
                if (index == 0) {
                    firstChainageVal = item.ChainageNo;
                }
                chainageDataKeys.push(item.ChainageNo);
                chainageDataValues.push(null);
            });
            for (var i = 0; i < chainageDataKeys.length; i++) {
                keyValues[chainageDataKeys[i]] = chainageDataValues[i];
            }
        }
    })
   
    $('#autocompleteInput').autocomplete({
        data: keyValues,
        onAutocomplete: function (val) {
            // Callback function when value is autcompleted.
            AutoCompleteSelectHandler(val)
        },
        selectFirst: true

    })

This is working but I couldn't select its value. I tried to set it using .val(), .value , .text() etc. Is there any way to set its value by default?

TBA

User $("#autocompleteInput").autocomplete().val().data('autocomplete') this for selecting a default value.

AJAX, which stands for asynchronous JavaScript and XML, is a technique that allows web pages to be updated asynchronously, which means that the browser doesn't need to reload the entire page when only a small bit of data on the page has changed.

So what actually was happening is, when I was using dummy data, it was there already and working perfectly fine. But in ajax call, everything else gets loaded before getting data (please go through this link about call stack to understand the behavior fully).

So what I did here is, after successfully getting the data then applied auto-complete.

Solution with ajax call:

$(document).ready(function(){
            var chainageDataKeys = [];
            var chainageDataValues = [];
            var keyValues = [];
            $.ajax({
                type: "GET",
                url: "https://restcountries.com/v3.1/all", // dummy ajax calling
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    $.each(response, function (index, item) {
                        if (index == 0) {
                            firstChainageVal = item.ccn3;
                        }
                        chainageDataKeys.push(item.ccn3);
                        chainageDataValues.push(null);
                    });
                    for (var i = 0; i < chainageDataKeys.length; i++) {
                        keyValues[chainageDataKeys[i]] = chainageDataValues[i];
                    }
                    //moved the autocomplete part here
                    $('#autocompleteInput').autocomplete({
                        data: keyValues,
                        onAutocomplete: function (val) {
                            // Callback function when value is autcompleted.
                        },
                        selectFirst: true
                    }).val(Object.keys(keyValues)[0]).data('autocomplete');
                }
            });
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css" rel="stylesheet"/>



<div class="input-field col s12">
        <label for="autocompleteInput">Chainage Number</label>
        <input type="text" id="autocompleteInput">
    </div>

Solution With Dummy Data:

//Just used some dummy data for testing

 var keyValues = 
{
"184": null,
"185.01": null,
"185.76": null,
"186.3": null
};

    $( "#autocompleteInput" ).autocomplete({
      data: keyValues,
        onAutocomplete: function (val) {
            // Callback function when value is autcompleted.
            
        },
        selectFirst: true
    }).val(Object.keys(keyValues)[0]).data('autocomplete'); 
    //this will take first item from keyValues as default value
    
    console.log(Object.keys(keyValues)[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css" rel="stylesheet"/>


<div class="input-field col s12">
                <label for="autocompleteInput">Chainage Number</label>
                <input type="text" id="autocompleteInput">
            </div>

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

how to set default initial value on nz-autocomplete

How to trigger jquery autocomplete clicking on input with existing value and default result for empty input

how can i set object list in default input value

Set default value for select input in php

Formtastic/ActiveAdmin set a default value for a select input

How to set default value in function

How to set default value for variable?

How to change default body color of materialize datetimepicker?

Set a default value for paper-input-container with custom logic

Set default value for @Input in case that it's null from departure

How to set a default value in a dropdown javascript

how to set initial(default) value in dropdownButton?

How to set default value of <p:selectOneMenu

How to set default value in laravel collective form

How to set default value for radio button in react?

how to set column in GridView to default value?

give default value to md-autocomplete

How to turn off input autocomplete?

How can I set the default date in input portion?

How to set my first value (default value) in spinner as empty

How to set input alphanumeric value format in input field reactjs?

Set default value of validation

Retrieve autocomplete input value from child component

PyQt5: How to input default value if QLineEdit is empty?

JavaScript/SASS: How to override default width of Google Maps API v3 Autocomplete dropdown based on width of input field?

How to set the default value of dropdown-menu base on URL param?

PHP: How can I set a default value for $_POST array?

How to set Django model date field default value to future date?

How to set default value as blank in dropdown along with items tag

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo