How to set default value in materialize autocomplete input? - javascript

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>

Related

Materialize autocomplete drop-down not working

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>

Populating razor text input from ViewData

Im trying to pre populate an input text box in a modal. Currently i click the edit button which calls a jQuery function that makes an ajax call
<script>
$(document).ready(function(){
$(".selectRow").click(function(e)
{
e.preventDefault();
var row = $(this).closest("tr"),
tds = row.find("td:nth-child(1)").first();
var textval = tds.text();
$.ajax({
url: "EditApplication?handler=GetRowInfo",
type: "POST",
dataType: "json",
data: { textval },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
alert("success");
},
complete: function () {
$('#editAppModal').modal('show');
},
failure: function () {
alert("failure");
}
})
});
});
</script>
On completion i show the modal. This jQuery function calls a method in the code behind called GetRowInfo which grabs a cell from a table.
GetRowInfo
public void OnPostGetRowInfo(string textval)
{
Console.WriteLine("-----------------"+textval);
DutyWeb dutyWebManager = new DutyWeb();
textval = textval.Trim();
Console.WriteLine("-----------------NEW-"+textval);
selectedRow = dutyWebManager.SearchByApplication(textval);
ViewData["appName"] = textval;
}
I assign the text value sent into the ViewData as appName
I then assign the textbox input value to be the ViewData["appName"
<div class="modal-body">
<input type="text" name="appName" id="appName" value='#ViewData["appName"]'>
<input type="text" name="appShortName" style="width:15%">
<br>
</div>
I dont know if im doing this wrong but it seems right to me. The modal is inside of a form element. Stepping through revealed that the ViewData is indeed storing the correct value, but its not being displayed in the textbox
I would like to avoid using jQuery to do this. I feel like ViewData is a much easier way of accomplishing the same task

Javascript Circular reference exception

I am trying to update the description field for a record in a database using a JQuery.change for the input on the view. However, after wiring up my clientside code I am now getting a circular reference exception when trying to stringify the JSON in order to make the ajax call. Any help would be greatly appreciated.
Here's the code:
<div class="divTableCell">
<label for="CheckRunDescription" id="checkRunDescriptionLabel">Description:</label>
<input type="text" id="CheckRunDescription" style="width: 270px;" />
</div>
The JQuery:
$('#CheckRunDescription')
.change(function() {
$(this).data("old", $(this).data("new") || "");
var newDetails = $(this).data("new", $(this).val());
updateCheckRunDetails(newDetails);
});
function updateCheckRunDetails(newDetails) {
var checkRunID = $('#checkRunID').val();
var js = JSON.stringify({ checkRunDetails:newDetails, checkRunID:checkRunID });
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: './PayInvoicesWS.asmx/UpdateCheckRunDetails',
data: js,
dataType: "json",
success: function (data) {
},
error: function (data) {
}
});
}
You are trying to stringify a jQuery object.
var newDetails = $(this).data("new", $(this).val());// returns `$(this)`
I am guessing you want the input value passed to the function
Try
$('#CheckRunDescription')
.change(function() {
var newDetails = $(this).val();
$(this).data("old", $(this).data("new") || "").data("new", newDetails );
updateCheckRunDetails(newDetails);
});

Reset the data after unchecking the checkbox

I have some results in div's ,each result has one checkbox associated with it, when a user click on single checkbox user, Current checked box's value is passed to another page using an ajax call and data is fetched and displayed in a hidden div box.
Now problem is, when user uncheck the checkbox it should remove the data associated with the checkbox.
My code is :
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
Ajax call
<script type="text/javascript">
$(document).ready(function()
{
$(".compare").change(function() {
if(this.checked) {
var check = $(this).val();
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').append(data);
}
});
}
});
});
Use something like this to empty the contents of the DIV
$('#compare_box').empty()
better way is to keep the reference map, something like this
$(document).ready(function() {
var boxes = {};
$(".compare").change(function() {
var check = $(this).val();
var data = $(this).closest('.box').clone();
if (this.checked) {
boxes[check] = data;
$('#comparebox').append(boxes[check]);
} else if (!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
});
});
EDIT - should be working (not tested)
var check = $(this).val();
if (this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType: 'JSON',
data: {
value: check
},
success: function(data) {
boxes[check] = $(data);
$('#compare_box').append(boxes[check]);
}
});
} else if(!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
DEMO

AJAX filled Select2 not clickable

I'm using Select2 for a project. The second select box gets filled depending on the selected item in the first box, as shown in the link below. However, I can't click the first item in the second select box for some reason. The only way for me to select the first item if I want to, is to first select a different user, and then back to the first. How can I solve this?
Video:
My code:
This is the first select box, getting filled by regular PHP (Laravel). Everything works fine here.
<div class="form-group">
<label for="select"> Partner: </label>
<select id="select" name="select" class="searchselect searchselectstyle">
#foreach($partners as $i => $partner)
<option {{$i == 0 ? 'selected' : ''}} value="{{$partner->id}}">{{$partner->name}}</option>
#endforeach
</select>
</div>
Here Is the second select box, with the error.
<div class="form-group" >
<label for="select2"> Hoofdgebruiker: </label>
<select id="select2" style="min-width: 200px;" name="select2" class="searchselect searchselectstyle">
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
var url = '/json/getusers';
var $post = {};
$post.id = $("select").val();
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: $post,
cache: false
}).done(function(data){
$('#select2')
.find('option')
.remove()
.end();
$.each(data, function(i, value) {
console.log(data);
$('#select2').append($('<option>').text(value.text).attr('value', value.id));
});
}
);
});
-
public function getusers(){
if(!isset($_POST['term'])){
$users = User::where('partner_id', $_POST['id'])->get();
}else{
$wildcard = '%'.$_POST['term'].'%';
$users = User::where('partner_id', $_POST['id'])->where('email', 'LIKE', $wildcard)->get();
}
$array = array();
foreach($users as $i => $user){
$array[$i] = array("id" => $user->id, "text" => $user->email);
}
return response()->json($array);
}
Check the case sensitivity of the key "id" in json data. Probably you return "ID" insteat of "id".
{"results":[{"id":"3","text":"Exampe 3"},{"id":"4","text":"Example 4"},{"id":"16","text":"Example 16"}]}
not like that
{"results":[{"ID":"3","text":"Exampe 3"},{"ID":"4","text":"Example 4"},{"ID":"16","text":"Example 16"}]}
I found a solution, which is the following:
<script type="text/javascript">
$(document).ready(function() {
$(".searchselect").select2();
search();
$("#select").change(function(){
search();
});
});
function search(){
var $post = {};
$post.id = $("#select").val();
$("#select2").select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
var query = {
term: params.term,
id: $post.id
};
return query;
},
url: '/json/getusers',
cache: false,
processResults: function (data) {
return {
results: data
};
}
}
});
}
</script>
Now I'm using the regular AJAX functionality built in Select2, it is all working as expected now!

Categories