JQuery Autocomplete not filling input with selected item - javascript

I have a jQuery UI Autocomplete which is being populated by a third party web service.
The autocomplete is working correctly, however when I select an item from the list the autocomplete input field goes blank.
The autocomplete is used to search an address, once selected the address gets split into its components which fill out the rest of the form.
So I have the following input field ids:
#FullAddress, #AddressLine1,#AddressLine2, #AddressSuburb,#AddressState, #AddressPostcode
with #FullAddress being the autocomplete field.
The web service returns an array of objects each containing key value pairs named pretty much as above.
Originally the JS code looked like:
$("#FullAddress").autocomplete({
source: "URL",
dataType: "JSONP",
autoFocus: true,
select: function (event, ui) {
$("#FullAddress").val(ui.item['FullAddress']);
$("#AddressLine1").val(ui.item['Line1']);
$("#AddressLine2").val(ui.item['Line2']);
$("#AddressSuburb").val(ui.item['Suburb']);
$("#AddressState").val(ui.item['State']);
$("#AddressPostcode").val(String(ui.item['Postcode']));
}
});
Which contacted the server and was returning results, but they were not being displayed in the dropdown:
Clicking any option filled out all fields with address data (you just couldn't see which address you selected) apart from #FullAddress which gets blanked out. i.e. in the image above once one was selected the "123 te" disappears.
I discovered the following to add to the create event which fixed the dropdown display issue, but did not fix the fact that the #FullAddress field gets blanked no matter what happens.
$("#FullAddress").autocomplete({
source: "URL",
dataType: "JSONP",
autoFocus: true,
create: function () {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
return $("<li>")
.append('<a>' + item.FullAddress + '</a>')
.appendTo(ul);
};
},
select: function (event, ui) {
$("#FullAddress").val(ui.item['FullAddress']);
$("#AddressLine1").val(ui.item['Line1']);
$("#AddressLine2").val(ui.item['Line2']);
$("#AddressSuburb").val(ui.item['Suburb']);
$("#AddressState").val(ui.item['State']);
$("#AddressPostcode").val(String(ui.item['Postcode']));
}
});
Does any one know any other reasons why the autocomplete input field would be emptying?
It does not appear to care whether or not an item was selected, no matter what happens on blur the field empties.
Thanks

If you add event.preventDefault(); as the first line in the select function that should stop the field emptying:
select: function (event, ui) {
event.preventDefault();
$("#FullAddress").val(ui.item['FullAddress']);
...
}

Related

Hiding fields based on email value AND boolean yes/no field using JavaScript

I have a Microsoft Power Apps Portals page on my portal that requires a bit of customization through JavaScript. I would like to hide fields based on an email address entered, which works fine. However, when the user enters the email domain that will show some fields, I would like to apply additional formatting.
Here is the code I currently have:
$(document).ready(function () {
$("#emailaddress1").change(onShowHideEmployeeFields);
onShowHideEmployeeFields();
});
function onShowHideEmployeeFields() {
var varEmail = $("#emailaddress1").val()
//alert(varEmail)
if (varEmail.includes("#example.org")) {
$('#xxx_employeeid').parent().parent().show();
$('#xxx_employeeid').prop('required', true);
$('#xxx_employeeid').closest(".control").prev().addClass("required");
$('#xxx_defaultfacilityid').parent().parent().show();
$('#xxx_defaultfacilityid').prop('required', true);
$('#xxx_defaultfacilityid').closest(".control").prev().addClass("required");
$('#xxx_positiontitle').parent().parent().show();
$('#xxx_officer').parent().parent().show();
$('#xxx_officer').prop('required', true);
$('#xxx_officer').closest(".control").prev().addClass("required");
$('#xxx_jopositiontitle').parent().parent().show();
}
else {
$('#xxx_employeeid').parent().parent().hide();
$('#xxx_defaultfacilityid').parent().parent().hide();
$('xxx_defaultfacilityid_label').parent().parent().hide();
$('xxx_positiontitle_label').parent().parent().hide();
$('#xxx_positiontitle').parent().parent().hide();
$('#xxx_officer').parent().parent().hide();
$('#xxx_jopositiontitle').parent().parent().hide();
}
}
The code works fine, however, I want to extend the code by showing the JO Position Title IF the Officer field has been marked as 'Yes' (it is a boolean yes/no radio checkbox field).
I've tried testing this component separately using the below code:
function onShowHideEmployeeFields() {
$('xxx_officer').change(function () {
var varJO = $("$xxx_officer").val();
//alert(varJO)
if (varJO === 'Yes') {
$('xxx_jopositiontitle').parent().parent().show();
}
else {
$('xxx_jopositiontitle').parent().parent().hide();
}
})
}
This code doesn't seem to do anything. Any thoughts on this issue?
Thank you!
AFAICT your question boils down to how can I check if a checkbox is checked?. The code you tried is on the right track, but that's not how you get a checkbox's state. A quick search turns up many many examples:
$('xxx_officer').change(function () {
var varJO = $("$xxx_officer").prop('checked');
if (varJO) {
$('xxx_jopositiontitle').parent().parent().show();
} else {
$('xxx_jopositiontitle').parent().parent().hide();
}
});
There are many, many examples of this here on SO, and I've voted to close this question as a duplicate.
How do I check whether a checkbox is checked in jQuery?
Get checkbox value in jQuery
get current state of check box jquery
Check if checkbox is checked with jQuery
Get checkbox selected state with JQuery
...

How to change order of files before form submit - Jquery / Javascript

I am not so familiar with Javascript / frontend and I use Jquery to get simple functionality done. My use case is as below.
User selects multiple files. User will have option to reorder the files (done through Jquery UI sortable along with file change). I have two challenges
I am capturing the change via start and update and trying to reset the files array. However on form submit, the files are going in original order. Should I submit the form from Javascript rather than direct submit button. If so, how do I tie these events together. I have code as below so far.
$( function() {
var startIndx, updtIndx, temp;
$( "#sortable" ).sortable({
update: function(event, ui) {
updtIndx = ui.item.index();
//alert('update: '+updtIndx)
},
start: function(event, ui) {
startIndx = ui.item.index();
//alert('start: ' + ui.item.index())
}
});
temp = files[startIndx];
files[startIndx] = files[updtIndx];
files[updtIndx] = temp;
$( "#sortable" ).disableSelection();
} );
When user clicks on Select Files again, and adds some more files, I am able to show the ul/li with more file names but how do I store reference to previous files to submit them all?

Make JQuery autocomplete Always show specific option

I am using a JQuery(1.9.1) autocomplete dropdown. I want the user to type a system name in the dropdown and have the dropdown be updated as the user adds characters. I also want there to be a default value of "Other" always present on the top of the dropdown regardless of what characters the user enters. Here is a screenshot of what it should look like:
Here is my ajax call for that :
$.ajax({
type: 'POST'
, url: '/test/get_BackendSystems'
, dataType: 'json'
, success: function (response) {
if (response.success) {
backend_systems = [];
$.each(response.backend_systems, function (id,system_object) {
backend_systems.push(system_object["system"]);
});
}
$("#BackEnd").autocomplete({
source: backend_systems,
open: function(){
$(this).data("autocomplete").menu.element.addClass("backend_dropdown");
$('.backend_dropdown').prepend('<li class="ui-menu-item" role="menuitem"><a class="ui-corner-all ui-add-new" tabindex="-1">Other</a></li>');
$('.backend_dropdown').width(432);
}
});
}
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Here is the corresponding html:
<div class='referral wrapper'>
<input list="POS_options" name="data[Account][backend_system]" type="text" class="required" placeholder="Back-End System" maxlength="150" id="BackEnd">
</div>
Thie drop down looks the way I want except whenever I click "Other" from the dropdown I get this error in the chrome console and "Other" does not populate the input text box: "Uncaught TypeError: Cannot read property 'data' of undefined". Clicking the other options works fine.
Anyone know what I am doing wrong or have an alternative way to get this type of drop down? I suspect the issue is something to do with the interaction of autocomplete with prepend, since all the options besides "Other" work fine. If there are other ways of doing this besides jquery autocomplete I would be open to trying that as well.
I would try to prepend the 'Other' option where you define array, like this:
$.ajax({
type: 'POST'
, url: '/test/get_BackendSystems'
, dataType: 'json'
, success: function (response) {
if (response.success) {
backend_systems = ["Other"];
$.each(response.backend_systems, function (id,system_object) {
backend_systems.push(system_object["system"]);
});
}
$("#BackEnd").autocomplete({
source: backend_systems,
open: function(){
$(this).data("autocomplete").menu.element.addClass("backend_dropdown");
$('.backend_dropdown').width(432);
}
});
}
}
);
I also removed the prepend li element
Have you seen the SO answer here? Always show a specific choice in jQuery Autocomplete even if it doesn't match input
The formatting is incorrect in the answer (Im still working through it to determine how the HTML format should appear) but it seems very similar to what you (and I!) are trying to accomplish.

Kendo UI Multiselect: Remove delete action on data binding

I have a Kendo multiselect UI element and I am trying to check a certain condition and make sure that element is non-deletable right at the initial data load. My code is as follows:
$scope.programSelect = $("#selectPrograms1").kendoMultiSelect({
dataSource:new kendo.data.DataSource({
data: $scope.programs
}),
dataTextField: "name",
dataValueField:"id",
select: addProgram,
dataBound: function (e) {
//check condition on data
//if true then do
//$(e.sender.tagList).find("li span.k-delete").remove();
},
change: programRemove
}).data("kendoMultiSelect");
I had some help from this link here. This piece of code doesn't seem to be working for some reason and I'm at a loss. Would appreciate any suggestions. Am I checking at the wrong place?

Tooltipster not working properly in the beginning

I am using the tooltipster plugin tool where I got gantt chart drawn with some td given id.
So, which ever id is defined and the mouse over it will get ajax data and show accordingly.
Below is snippet of my codes. Issue here is that the tool tip only appear after few times I mouse the td. Thereafter, it works fine.
I can see, in my debug window, that ajax page is called and following error:
Tooltipster: one or more tooltips are already attached to this element: ignoring. Use the "multiple" option to attach more tooltips. jquery.tooltipster.min.js:1
$(document).ready(function () {
$('td[id]').tooltipster({
// content: 'Loading...',
functionBefore: function(origin, continueTooltip) {
// We'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data
continueTooltip();
var idval=0;
// Next, we want to check if our data has already been cached
//if (origin.data('ajax') !== 'cached') {
$.ajax({
type: 'GET',
url: 'getDetails.php',
data:idval,
success: function(data) {
// Update our tooltip content with our returned data and cache it
//alert("Data is : "+data);
var finalData = 'Total Data : 300 <br> Total Completed : 200';
//alert("DATA");
//origin.tooltipster: $('<span>testst<strong>This text is in bold case !</strong></span>')
origin.tooltipster({
content: finalData,
multiple: true,
contentAsHTML: true
});
//origin.tooltipster({content: data,contentAsHTML: true}).data('ajax', 'cached');
}
});
//}
}
});
});
The Tooltipster plugin really should be initialised before all of this. Using the mouseenter enter to trigger it's initialisation every time a user hover's over a <td> element is not great practice and is the root problem to your issue. Ideally you would want to break it down into the following:
Find your <td> elements with id's defined.
Apply tooltipster to these elements.
Let tooltipster handle everything from there.
1. Finding your <td> elements
With the magic of jQuery you can fetch these with a clever use of selectors rather than querying a larger set with your initial implementation, gathered from the answers within the StackOverflow thread here, jquery get only all html elements with ids, we get:
$('td[id]')
This will fetch you all <td> elements with an id defined, be warned this could be a bit slow if you have an extensive table. Alternatively you can select, then apply a filter to narrow down your set:
$('td').filter(function(){
return $(this).attr('id') !== undefined;
});
Both will essentially do the same!
2. Applying tooltipster to these elements
I've not done much here since you had a lot of commented out code, so I've kept it the same, with some minor tweaks, here is my version of the "working code":
$('td[id]').tooltipster({
// content: 'Loading...',
functionBefore: function(origin, continueTooltip) {
// We'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data
continueTooltip();
// Next, we want to check if our data has already been cached
//if (origin.data('ajax') !== 'cached') {
$.ajax({
type: 'GET',
url: 'getDetails.php',
data: $(this).attr('id'),
success: function(data) {
// Update our tooltip content with our returned data and cache it
//alert("Data is : "+data);
var finalData = 'Total Data : 300 <br> Total Completed : 200';
//alert("DATA");
//origin.tooltipster: $('<span>testst<strong>This text is in bold case !</strong></span>')
origin.tooltipster({
content: finalData,
multiple: true,
contentAsHTML: true
});
//origin.tooltipster({content: data,contentAsHTML: true}).data('ajax', 'cached');
}
});
//}
}
});
3. Letting tooltipster handle everything from here
Tooltipster (when intialised) is triggered by default when hovering over an element, this means your functionBefore will be run before this "hover" event, causing your AJAX request to be run each time, there is no need to do anything more thereafter :D
I hope this helps! :)
You can use this code :
var tooltipInstance;
$("body").on('mouseover', 'td[id]:not(.tooltipstered)', function(){
tooltipInstance = $(this).tooltipster({
//your code ...
});
tooltipInstance.tooltipster('open');
});

Categories