Make JQuery autocomplete Always show specific option - javascript

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.

Related

How to upload and display only one file in Dropzone.js and jsGrid?

I have a Dropzone control and a jsGrid control. Files that are dragged to the Dropzone are displayed in jsGrid. I want only one file to be uploaded and after it, there should be no option to upload files. Now it can be solved by the following approach.
Every time the change event is triggered on jsGrid, no. of rows in jsGrid are counted. Dropzone is enabled if the count is 0 and disabled if the count is 1. I can't seem to find the code for counting the no. of rows in jsGrid. Kindly help me with the code.
Also, let me know if there's another way to solve it.
Here's the screenshot of my form:
Thanks in advance.
I have solved the issue by using CSS to disable the Dropzone control.
.maxFilesReached {
pointer-events: none;
cursor: default;
background-color: #ffd9d8
}
This CSS class is added to the jsGrid loadData event upon success.
loadData: function (filter) {
return $.ajax({
type: "POST",
url: "/Downloads/GetDownloadItems/" + DownloadId,
data: filter,
dataType: "json"
}).done(function (response) {
debugger;
if (response.length == 1) { // disabling Dropzone control
$("#dropzoneForm").addClass('maxFilesReached');
}
});
}
Similarly, the CSS class is removed upon the deleteItem event of jsGrid.
deleteItem: function (item) {
return $.ajax({
type: "POST",
url: "/Downloads/DDownloadItem/" + item.Id,
dataType: "json"
}).done(function () {
// enabling Dropzone control
$("#dropzoneForm").removeClass('maxFilesReached');
});
}
I have also used the maxFiles property of Dropzone to prevent more than one uploads.
P.S. jsGrid is kind of messy.

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');
});

Jquery Checkbox custom event does not return stable result

Hi I'm working on a custom blogsite I have a working script here for my checkbox. But my checkbox does not have the attrib checked by default because my page displays first the actual article then the checkbox is labeled as "edit" so when a user clicks on it the article will be loaded on my textarea(It has TinyMCE plugin for editing purpose) the user can now edit the article.. This will be used to check if someone is editing it already FYI
Here is my script:
$("#edit").on('change', function(e){
$("#viewmode").toggle(function(){
$.ajax({
type: 'GET',
url: 'includes/edittyp.php',
data: "flag="+0,
success: function (status) { }
});
});
$("#viewmode").toggleClass('display: none' );
$("#editmode").toggle(function(){
$.ajax({
type: 'GET',
url: 'includes/edittyp.php',
data: "flag="+1,
success: function (status) { }
});
});
$("#editmode").toggleClass('display: block' );
My issue is this script updates the flag to 1 whenever $("#editmode") is toggled and it updates to 0 whenever $("#viewmode") is also clicked but this works only once because after I refreshed the page the viewmode returns 1 and editmode returns 0 or it does not change at all.. Can someone please point out where did I go wrong or are there other way/s on how can achieve this
Thanks

Inconsistent results when loading HTML snippet into select tag

I'm using Ajax to load the contents of a select:
<select id = "idResultEntryMeet" class="form-control input-md" size = 1>
</select>
...
$('#idResultEntryMeet').mousedown(function() {
$.post("/cgi-bin/listOptions", function(data) {
$('#idResultEntryMeet').html(data);
});
});
This isn't consistent across browsers, which makes me think that there's a problem with the code:
IE9 never shows anything in the select
FF 27 works as expected
Chrome and IE11 don't show anything in the pull-down on the first
mouse click, but will show the expected contents on the second mouse
click. I can fix this on both browsers by pre-loading the select
during the initial page load
Opera and Safari require a second mouse click, even with an initial preload
Any suggestions on what's wrong with this?
EDIT
Sorry, guess this wasn't obvious: the select must be dynamic. The options are constantly changing, depending on the contents of a database. The idea is that the user sees the current options when they click the pull-down on the select. Using a click (instead of mousedown) handler doesn't work, since the user can't then actually select anything they see in the pull-down.
And the CGI code returns an HTML snippet, containing the options. Firebug shows a correctly-formed select containing options on completion of the POST.
EDIT
The problem is that the Ajax request has to be synchronous (Sjax?) (as more-or-less suggested in the comments), to prevent interfering with whatever happens when the select pull-down is activated. This code works with proper browsers (and almost works in IE9), but changing async to true causes consistent problems with various browsers:
$('#idResultEntryMeet').mousedown(function() {
$.ajax({
type : "POST",
url : "/cgi-bin/listOptions",
async : false
}).done(function(data, textStatus, jqXHR) {
$('#idResultEntryMeet').html(data);
});
});
Try that (just tested on chrome):
$('#idResultEntryMeet').on('mousedown', function(e){
if(!e.view) return;
e.preventDefault();
var _self = this;
$.post("/cgi-bin/listOptions", function (data) {
$(_self).html(data);
var mdwn = document.createEvent("MouseEvents");
mdwn.initMouseEvent("mousedown", false, false, null, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
_self.dispatchEvent(mdwn);
});
});
Simplified DEMO
EDIT: doesn't work on FF nor IE...
Try change your code for:
html
<select id="idResultEntryMeet" class="form-control input-md" size="1">
</select>
js
$(document).ready(function() {
$.post("/cgi-bin/listOptions", function(data) {
$('#idResultEntryMeet').html(data);
});
});
$('#idResultEntryMeet').change(function() {
var valueSelected = $(this).val();
alert(valueSelected);
//Do something
});
Edit:
you need include the delegate bind with jquery for do this dinamic.
$('#idResultEntryMeet').bind("click", function() {
var data = '<option value="volvo">Volvo</option><option value="saab">Saab</option>';
$('#idResultEntryMeet').html(data);
});
And need format the return of the method some like this

How can I write a function that relies on dynamic selectors?

I am writing a function to dynamically load jQuery UI accordian leaves with content. I know (think) the AJAX part works as I lifted it from another working AJAX loader I have, but the function as a whole does not work.
The code:
function load_leaf(link){
var link = link;
$.ajax({
cache : false,
type : 'POST',
async: false,
url : 'includes/'+ link +'.php?'+ new Date().getTime(),
dataType : 'text',
data: {
owner : '$user_id'
},
success: function(msg){
$("#" + link).html(msg);
console.log('Can\'t see me in Chrome, but ok in firefox !')
},
error: function() {
console.log($.makeArray(arguments));
},
complete: function() {
console.log($.makeArray(arguments));
}
});
};
$(function(){
$('.accordian').click(function(){
var link = this.getAttribute("link");
load_leaf(link);
});
});
For whatever reason this does not work. The break point seems to be this line
$("#" + link).html(msg);
Specifically the selector, as a hard coded selector works perfectly. The link variable is correctly filled i know this as i can alert the value correctly. The link is not the problem as i replaced the whole ajax function with a simple add class and it a still did not work, it also broke at the selector.
EDIT:
This is the div as printed by php:
<h3 class="accordian" id="'.$tab_id.'" link="'.$tab_link.'" >
'.$tab_name.'
</h3>
<div id="'.$tab_link.'"><p>Hi</p></div>
The html for the first one is:
<h3 class="accordian" id="accordian_manage.php" link="accordian_manage.php" >Manage Images</h3><div id="accordian_manage.php"><p>Hi</p></div>
Your ID has a period . in it, which jQuery interprets as a chained class selector.
You can either change your link/IDs, or use this hack:
$("[id='" + link + "']");
Live demo
I guess your problem is with Jquery is not finding the div to load the msg..Post the accordion div so that i could give you the proper selector

Categories