Materialize autocomplete drop-down not working - javascript

I have been working with materialize autocomplete for my project and I have been running into issues with getting the dropdown to appear. It just fails to appear! I read that materialize version 0.98.2 might work, I used that CDN and it still doesn't work. I suspect there is some problem with triggering the dropdown. (I could be very wrong) another thing that could be wrong is that the data isn't being used because I messed up somewhere.
I am having no problem getting the data and using that, but the dropdown just wnt work.
html:
<div class="input-field">
<label for="country">Autocomplete</label>
<input type="text" id="company" class="autocomplete">
</div>
here is my js:
var company = document.getElementById("company");
company.addEventListener("input", function () {
$(function() {
var inputValue = $('#company').val();
var url = 'https://sandbox.iexapis.com/stable/search/'
+ encodeURIComponent(inputValue)
+ '/?token=****************';
$.ajax({
type: 'GET',
url: url,
success: function(response) {
var companyArray = response;
var dataCompany = {};
for (var i = 0; i < companyArray.length; i++) {
//console.log(countryArray[i].name);
console.log(url);
dataCompany[companyArray[i].securityName] = companyArray[i].symbol;
console.log(companyArray[i].securityName);
console.log(companyArray[i].symbol);
}
$('input.autocomplete').autocomplete({
data: dataCompany
});
}
});
});
});
Since someone requested the response I am putting some screenshots here!
this is when I enter "wa"
the problem is not that the data isn't there, it's just that the dropdown selector box fails to appear.

You can first intialize your autocomplete and store instance of that in some variable . Then , whenever user type inside input-box simply use that instance to update data inside your autocomplete i.e : instance.updateData(dataCompany) .
Demo Code :
//suppose this is response return from ajax
var response = [{
"securityName": "abc",
"symbol": "scsc"
}, {
"securityName": "abc2",
"symbol": "scsc2"
}]
$(function() {
$('input#company').autocomplete() //intialize your autocomplete
let instance = M.Autocomplete.getInstance($('input#company')); //get instance
$('input.autocomplete').on("input", function() {
var inputValue = $('#company').val();
/*var url = 'https://sandbox.iexapis.com/stable/search/' +
encodeURIComponent(inputValue) +
'/?token=****************';
$.ajax({
type: 'GET',
url: url,
success: function(response) {*/
var companyArray = response;
var dataCompany = {};
for (var i = 0; i < companyArray.length; i++) {
dataCompany[companyArray[i].securityName] = companyArray[i].symbol;
}
//updatedata
instance.updateData(dataCompany)
/* }
});*/
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="input-field">
<label for="country">Autocomplete</label>
<input type="text" id="company" class="autocomplete" autocomplete="off">
</div>

Related

Ajax trigger keyup function changing to instant trigger

i'm trying to get details information from database according to input from id_card .
im already succeed getting the information after I'm typing the id_card in the input box by using keyup function. What i need to do now is I want result appear without I have to press any key after input was trigger. As information, the input will fill in by using QR scanner.
My HTML
<input type="text" id="id_card" placeholder="Capture by QR Code Scanner" name="id_card">
<input type="text" id="fullname" placeholder="Staf Name" name="fullname" readonly>
My Ajax
$(document).ready(function() {
$('#id_card').keyup(function() {
var id_card = $(this).val();
$.ajax({
url: "<?php echo base_url('index.php/scan/get_details'); ?>",
method: 'post',
data: {id_card: id_card},
dataType: 'json',
success: function(response) {
var len = response.length;
document.getElementById("fullname").value = "";
if (len > 0) {
$("#id_card").load();
var uname = response[0].id_card;
var name = response[0].fullname;
document.getElementById("fullname").value = response[0].fullname;
}
}
});
});
});
I'm trying to change keyup function to onchange but no luck.
Thank you for helping.
Try
$(function() {
$('#id_card').on("input", function(e) { // pasted or typed
let id_card = $(this).val();
if (id_card.replace(/\D+/g).length < 16) return
// here the ajax

How to set default value in materialize autocomplete input?

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?
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>

Get select multiple values with JQuery

I have a problem with JQuery, I have a multiple select that i can populate in 2 ways, manually taking some value from another select with a add button, and dynamically, with parsing a json returned from a spring call.
I have no problem to take the value when I add it manually, but, when I populate dynamically the select, the JQuery code doesn't take any value although int the html code there're values in the select.
Here my code:
The empty html selects
<div id="enti_disp_box">
<label>Enti disponibili</label>
<select id="ente" multiple> </select>
<button class="btn" onclick="addEnteInBox();" type="button">Aggiungi</button>
</div>
<div id="enti_att_box">
<label>Enti attivi*</label>
<select id="entiAttivi" multiple></select>
<button class="btn" onclick="removeEnteInBox();" type="button">Rimuovi</button>
</div>
JQuery for populate the second select manually
function addEnteInBox(){
var selectedOptions = document.getElementById("ente");
for (var i = 0; i < selectedOptions.length; i++) {
var opt = selectedOptions[i];
if (opt.selected) {
document.getElementById("entiAttivi").appendChild(opt);
i--;
}
}
}
function removeEnteInBox(){
var x = document.getElementById("entiAttivi");
x.remove(x.selectedIndex);
}
JQuery for populate the second select dynamically
function getEntiByIdUtente(idutente) {
var action = "getEntiByidUtente";
var payload = {
"idUtente": idutente,
"action": action,
"token": token
};
$.ajax({
type: "POST",
url: '../service/rest/enti/management_utenti',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(payload),
resourceType: 'json',
success: function(obj, textstatus) {
obj = obj.trim();
var json = JSON.parse(obj);
//parse response
if (obj.stato == 'error') {
alert('Errore');
} else {
$('#entiAttivi').empty();
//fetch obj.data and populate table
$(json.data).each(function() {
$("#piva").val(this.piva);
$("#codiceipa").val(this.codiceipa);
$('#entiAttivi').append($('<option>', {
value: this.idente,
text: this.ragionesociale
}));
});
}
return json;
},
error: function(obj, textstatus) {
alert('Errore di comunicazione col server!');
}
});
}
JQuery for taking the value of the second select
var entiList = $("#entiAttivi").val();
This line seems to be wrong, it's not working for me
$('#entiAttivi').append($('<option>', {
value: this.idente,
text: this.ragionesociale
}));
would you try replacing by
$('#entiAttivi').append($('<option value="' + this.idente + '">' + this.regionesociale + '</option>');
The append, is trying to create an option with the json as parent, this is not working. please try my code.

Autocomplete ajax is not working

<script>
function autocomplet1() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#select01').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'barcode.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#barcode01').show();
$('#barcode01').html(data);
}
});
} else {
$('#barcode01').hide();
}
}
function set_item(item2) {
$('#select01').val(item2);
var customer = $("#customer").val();
$.post("sales/add", {"data[Sales][item]": item2 ,"data[Sales][customer_phone]": customer }, function (data) {
$('#details3').html(data);
$("#select01").val('');
});
// hide proposition list
$('#barcode01').hide();
}
</script>
<script>
// autocomplet : this function will be executed every time we change the text
function autocomplet() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#customer').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'abc.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
}
function set_item(item1) {
$('#customer').val(item1);
$.post("sales/add", {"data[Sales][customer]": item1 }, function (data) {
$('#details').html(data);
});
// hide proposition list
$('#country_list_id').hide();
}
</script>
<div class="input_container">
<input type="text" id='customer' onkeyup="autocomplet()" name="data[Sales][customer]" class="input-small focused">
<ul id="country_list_id" style='height: 500px;'></ul></div></div>
<div class="content">
<div class="input_container">
<input type="text" id='select01' onkeyup="autocomplet1()" name="data[Sales][item]" class="input-small focused">
<ul id="barcode01" style='height: 500px;'></ul></div></div>
Above is an autocomplete script. Both script having same function set_time . If i changed function name as set_time1, then autocomplete is not working . How to resolve this issue? . I need to use two autocomplete in a single page.
Okay, since this is hard to explain in the tiny comments, I'll write it here.
Take that script :
function set_item(){
alert("Hello!");
}
function set_item(){
alert("Goodbye!");
}
set_item();
What do you think will happen? What will be alerted?
Answer : "Goodbye!", because the second function definition overrode the first one. You will never see the "Hello!" alert.
This is what happens when two functions have the same name. And you have two functions with the same name. Placing them in different <script> tags won't change anything, it's still the same scope.

Highlight live search results

I'm trying to highlight the text that matches the query in a live search using jquery.highlight. The live search works fine but the styling for the highlighting applies then it disappears. Am I doing something wrong?
JQuery
$(document).ready(function() {
$("#search").bind("keyup", function() {
var form = $(this).parents("form");
var query = $(this).val();
var formData = form.serialize();
$.post("/questions/new/search", formData, function(html) {
$("#questionList").html(html);
});
$(".question").highlight(query);
});
});
HTML
<form action="/questions" method="get">
<input id="search" name="search" type="text" />
</form>
<div id="questionList">
<div class="question">What is the 1 + 1?</div>
<div class="answers">2</div>
</div>
Yes, you should execute $(".question").highlight(query) in the http request response handler right after $("#questionList").html(html) this way:
$(document).ready(function() {
$("#search").bind("keyup", function() {
var form = $(this).parents("form");
var query = $(this).val();
var formData = form.serialize();
$.post("/questions/new/search", formData, function(html) {
$("#questionList").html(html);
$(".question").highlight(query);
});
});
});

Categories