PrimeNG dropdown dynamic options and preselected item on event fired not work the first time but works in the next times - binding

If dropdown options are assigned dynamically as a response of an event, the select option is always the first one the first time that event is fired and in all next executions, the selected option is correct. If an idle time is used, the behavior is the expected.
Run the stackblitz example and click in the button to confirm that the preselection is wrong (always the first element of the list) but then, the second time (and all other times after) the correct value is bind. Another "curious" fact is that if we comment the line for assign the preselected item and uncomment the setTimeout() line (meaning doing the assignment after a very short idle time), it works as expected.
https://stackblitz.com/edit/primeng-dropdown-demo-n9ynk8
How should I do the bind avoiding the idle time?
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
options: Array<number> = [];
value: number;
constructor() {}
buttonOnClick() {
this.options = [1, 2, 3];
this.value = 3;
//setTimeout(() => { this.value = 3; }, 10);
}
}
<p-button (onClick)="buttonOnClick()">Bind Dropdown</p-button>
<br />
<p-dropdown
id="demoDropdown"
[options]="options"
[(ngModel)]="value"
></p-dropdown>

PrimeNG dropdown component have a property called: "autoDisplayFirst" activated by default that as its name suggest it auto-preselect the first option always. To solve the issue we need to disable that feature:
<p-dropdown
id="demoDropdown"
[options]="options"
[(ngModel)]="value"
[autoDisplayFirst]="false"
></p-dropdown>

Related

SAPUI5 Table Cell Custom Control Binding

I was wondering if someone could shed some light on the issue I am having. I can't seem to get the data model updated when I use my custom input control in a cell. When using the standard sap.m.Input, updates to the data model are performed properly.
Here is the Plunker: https://plnkr.co/edit/GxE6F8DbW9DHqWjpfdO0
I have overrriden the getter for the 'value' properly to get the data from the entry field. Debugging in Chrome shows that this function is not called which I believe is the reason the data model is not updated.
getValue: function() {
var me = this;
var ef = sap.ui.getCore().byId(me.sId + '-ef');
return ef.getProperty('value');
}
Basically, there is a table with two rows and four columns. The first column uses my custom input. The second column has a custom button with an aggregation (additionalParameters) containing the bound data used in the first column. The third column uses a standard sap.m.Input and lastly the fourth column is again a custom button with the 'additionalParameters' aggregation bound to the data in the third column. When any of the buttons are pressed it fires an event which in turn updates the 'Sample' input field.
So, when I type something in the first column, tab out and press the respective 'PB1' button, only the original data from the model appears in the 'Sample' input field. If I type something in the third column, tab out of the field and press the respective 'PB2' button, the 'Sample' input field is properly set by the newly entered data implying the data model has been updated.
Edit
I can get the value from the Input no problem. Maybe I can clarify. The 'MyCustomInput' in cell 1 has 'value' bound to 'list>colOne'. The 'MyCustomButton' in cell 2 has the 'text' of the first item in aggregation 'additionalParameters' bound to the same 'list>colOne'. Any text entered into MyCustomInput does not update the model and thus does not update the 'additionalParameters' item. If I do the exact same thing but use a standard Input instead of MyCustomInput it works. As can be seen with the Input in Cell 3 and the button in Cell 4.
Thank you
May be you can provide more information. We have a simple example here
http://jsbin.com/yukujag/edit?html,js,output and it works on with getValue and setValue
sap.ui.define(['sap/m/Input', 'sap/m/Button', 'sap/m/VBox'],
function(Input, Button, VBox) {
Input.extend('MyInput', {
value: 'abc',
renderer: {},
getValue: function() {
return this.value;
},
setValue: function(v) {
this.value = v;
},
});
var oInput = new MyInput();
var oBox = new VBox({
items: [
oInput,
new Button({
text: 'Test',
press: function() {
alert(oInput.getValue());
}
})
]
})
oBox.placeAt('content');
});
Thanks
-D

How to use jQuery UI with React JS

How can I use jQuery UI with React? I have seen a couple examples by Googling, but all of them seem to be outdated.
If you really need to do that, here is an approach I am using.
The plan: Create a component to manage the jQuery plugin. This component will provide a React-centric view of the jQuery component. Moreover, it will:
Use React lifecycle methods to initialize and tear down the jQuery plugin;
Use React props as plugin configuration options and hook up to plugin's methods events;
Destroy the plugin when component unmounts.
Let's explore a practical example how to do that with the jQuery UI Sortable plugin.
TLDR: The Final Version
If you just want to grab the final version of the wrapped jQuery UI Sortable example:
here is a GIST I made with full annotated comments;
and here's a jsfiddle DEMO, full annotated comments too;
... plus, below is the shortened from the longer comments code snippet:
class Sortable extends React.Component {
componentDidMount() {
this.$node = $(this.refs.sortable);
this.$node.sortable({
opacity: this.props.opacity,
change: (event, ui) => this.props.onChange(event, ui)
});
}
shouldComponentUpdate() { return false; }
componentWillReceiveProps(nextProps) {
if (nextProps.enable !== this.props.enable)
this.$node.sortable(nextProps.enable ? 'enable' : 'disable');
}
renderItems() {
return this.props.data.map( (item, i) =>
<li key={i} className="ui-state-default">
<span className="ui-icon ui-icon-arrowthick-2-n-s"></span>
{ item }
</li>
);
}
render() {
return (
<ul ref="sortable">
{ this.renderItems() }
</ul>
);
}
componentWillUnmount() {
this.$node.sortable('destroy');
}
};
Optionally, you can set default props (in the case of none are passed) and the prop types:
Sortable.defaultProps = {
opacity: 1,
enable: true
};
Sortable.propTypes = {
opacity: React.PropTypes.number,
enable: React.PropTypes.bool,
onChange: React.PropTypes.func.isRequired
};
... and here's how to use the <Sortable /> component:
class MyComponent extends React.Component {
constructor(props) {
super(props);
// Use this flag to disable/enable the <Sortable />
this.state = { isEnabled: true };
this.toggleEnableability = this.toggleEnableability.bind(this);
}
toggleEnableability() {
this.setState({ isEnabled: ! this.state.isEnabled });
}
handleOnChange(event, ui) {
console.log('DOM changed!', event, ui);
}
render() {
const list = ['ReactJS', 'JSX', 'JavaScript', 'jQuery', 'jQuery UI'];
return (
<div>
<button type="button"
onClick={this.toggleEnableability}>
Toggle enable/disable
</button>
<Sortable
opacity={0.8}
data={list}
enable={this.state.isEnabled}
onChange={this.handleOnChange} />
</div>
);
}
}
ReactDOM.render(<MyComponent />, document.getElementById('app'));
The Full Explanation
For those of you, who want to understand why and how. Here's a step by step guide:
Step 1: Create a component.
Our component will accept an array (list) of items (strings) as data prop.
class Sortable extends React.Component {
componentDidMount() {
// Every React component has a function that exposes the
// underlying DOM node that it is wrapping. We can use that
// DOM node, pass it to jQuery and initialize the plugin.
// You'll find that many jQuery plugins follow this same pattern
// and you'll be able to pass the component DOM node to jQuery
// and call the plugin function.
// Get the DOM node and store the jQuery element reference
this.$node = $(this.refs.sortable);
// Initialize the jQuery UI functionality you need
// in this case, the Sortable: https://jqueryui.com/sortable/
this.$node.sortable();
}
// jQuery UI sortable expects a <ul> list with <li>s.
renderItems() {
return this.props.data.map( (item, i) =>
<li key={i} className="ui-state-default">
<span className="ui-icon ui-icon-arrowthick-2-n-s"></span>
{ item }
</li>
);
}
render() {
return (
<ul ref="sortable">
{ this.renderItems() }
</ul>
);
}
};
Step 2: Pass configuration options via props
Let's say we want to configure the opacity of the helper while sorting. We'll use the opacity option in the plugin configuration, that takes values from 0.01 to 1.
class Sortable extends React.Component {
// ... omitted for brevity
componentDidMount() {
this.$node = $(this.refs.sortable);
this.$node.sortable({
// Get the incoming `opacity` prop and use it in the plugin configuration
opacity: this.props.opacity,
});
}
// ... omitted for brevity
};
// Optional: set the default props, in case none are passed
Sortable.defaultProps = {
opacity: 1
};
And here's how we can use the component in our code now:
<Sortable opacity={0.8} />
The same way, we can map any of the jQUery UI Sortable options.
Step 3: Hook-up functions on plugin events.
You will most probably need to hook-up on some of the plugin methods, in order to perform some React logic, for example, manipulate the state let's day.
Here's how to do that:
class Sortable extends React.Component {
// ... omitted for brevity
componentDidMount() {
this.$node = $(this.refs.sortable);
this.$node.sortable({
opacity: this.props.opacity,
// Get the incoming onChange function
// and invoke it on the Sortable `change` event
change: (event, ui) => this.props.onChange(event, ui)
});
}
// ... omitted for brevity
};
// Optional: set the prop types
Sortable.propTypes = {
onChange: React.PropTypes.func.isRequired
};
And here's how to use it:
<Sortable
opacity={0.8}
onChange={ (event, ui) => console.log('DOM changed!', event, ui) } />
Step 4: Pass the future updates control to jQuery
Right after ReactJS adds the element in the actual DOM, we need to pass the future control to jQuery. Otherwise, ReactJS will never re-render our component, but we don't want that. We want jQuery to be responsible for all updates.
React lifecycle methods comes to the rescue!
Use shouldComponentUpdate() to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority, but we don't want this behavior!
shouldComponentUpdate() is invoked before rendering when new props or state are being received. If shouldComponentUpdate() returns false, then componentWillUpdate(), render(), and componentDidUpdate() will not be invoked.
Then, we use componentWillReceiveProps(), we compare this.props with nextProps and call jQuery UI sortable updates only when necessary. For this example, we will implement the enable/disable option of the jQuery UI Sortable.
class Sortable extends React.Component {
// Force a single-render of the component,
// by returning false from shouldComponentUpdate ReactJS lifecycle hook.
// Right after ReactJS adds the element in the actual DOM,
// we need to pass the future control to jQuery.
// This way, ReactJS will never re-render our component,
// and jQuery will be responsible for all updates.
shouldComponentUpdate() {
return false;
}
componentWillReceiveProps(nextProps) {
// Each time when component receives new props,
// we should trigger refresh or perform anything else we need.
// For this example, we'll update only the enable/disable option,
// as soon as we receive a different value for this.props.enable
if (nextProps.enable !== this.props.enable) {
this.$node.sortable(nextProps.enable ? 'enable' : 'disable');
}
}
// ... omitted for brevity
};
// Optional: set the default props, in case none are passed
Sortable.defaultProps = {
enable: true
};
// Optional: set the prop types
Sortable.propTypes = {
enable: React.PropTypes.bool
};
Step 5: Clean up the mess.
Many jQuery plugins provide a mechanism for cleaning up after themselves when they are no longer needed. jQuery UI Sortable provides an event that we can trigger to tell the plugin to unbind its DOM events and destroy. React lifecycle methods comes to the rescue again and provides a mechanism to hook into when the component is being unmounted.
class Sortable extends React.Component {
// ... omitted for brevity
componentWillUnmount() {
// Clean up the mess when the component unmounts
this.$node.sortable('destroy');
}
// ... omitted for brevity
};
Conclusion
Wrapping jQuery plugins with React is not always the best choice. However, it is nice to know that it is an option and how you can implement a solution. It is a viable option if you are migrating a legacy jQuery application to React or maybe you just can't find a React plugin that suits your needs in your case.
In the case that a library modifies the DOM, we try to keep React out of its way. React works best when it has full control of the DOM. In these cases, React components are more of wrappers for the 3rd party libraries. Mostly by using the componentDidMount/componentWillUnmount to initialize/destroy the third party library. And props as a way of giving the parent a way of customizing the behavior of the third party library that the child wraps and to hook-up on plugin events.
You can use this approach to integrate almost any jQuery plugin!
React doesn't play well with libraries that do direct DOM mutations. If something else mutates the DOM where React is attempting to render, it will throw errors. If you had to make this work, your best compromise is to have different parts of your page which are managed by different things, for example a div which houses your jquery component(s), and then some other div which contains your React component(s). Communicating between these disparate (jquery and react) components will be difficult however and honestly it's probably better to just choose one or the other.
While technically faultless, Kayolan's answer has a fatal flaw, IMHO: in passing the responsibility for future UI updates from React to jQuery, he's rather negated the point of React being there in the first place! React controls the initial render of the sortable list, but after that React's state data will become outdated as soon as the user does the first jQueryUI drag/sort operations. And the whole point of React is to represent your state data at the view level.
So, I took the reverse approach when I approached this problem: I tried to ensure that React was in control as much as possible. I don't let the jQueryUI Sortable control change the DOM at all.
How's that possible? Well jQuery-ui's sortable() method has a cancel call that sets the UI back to how it was before you started dragging and dropping stuff around. The trick is to read the state of the sortable control before you issue that cancel call. That way, we can pick up what the user's intentions were, before the cancel call sets the DOM back the way it was. Once we have those intentions, we can pass them back to React, and manipulate the state data to be in the new order that the user wanted. Finally, call a setState() on that data to have React render the new order.
Here's how I do that:
Attach the jquery-ui.sortable() method to a list of line items (generated by React of course!)
Let the user drag and drop those line items around the DOM.
When the user starts dragging, we read the index of the line item that user's dragging from.
When the user drops the line item, we:
Read from jQuery-ui.sortable() the new index position for the line item, i.e. where in the list user dropped it.
Pass a cancel call to jQuery-ui.sortable() so that the list goes backs to its original position, and the DOM is unchanged.
Pass the old and new indexes of the dragged line item as parameters to a JavaScript function in a React module.
Have that function reorder the list's back-end state data to be in the new order that the user dragged and dropped it into.
Make a React setState() call.
The list in the UI will now reflect the new order of our state data; this is standard React functionality.
So, we get to use jQueryUI Sortable's drag and drop functionality, but without it changing the DOM at all. React's happy, because it's in control of the DOM (where it should be).
Github repository example at https://github.com/brownieboy/react-dragdrop-test-simple. This includes a link to a live demo.
I could not get the jquery-ui npm package to work. What has worked for me is to use jquery-ui-bundle:
import $ from 'jquery';
import 'jquery-ui-bundle';
import 'jquery-ui-bundle/jquery-ui.min.css';
Concerning to Kaloyan Kosev's long answer, i must create a component for every jQueryUi feature that i want to use? No thanks! Why not simply update your state when you change the DOM? Followig works for me:
export default class Editor extends React.Component {
// ... constructor etc.
componentDidMount() {
this.initializeSortable();
}
initializeSortable() {
const that = this;
$('ul.sortable').sortable({
stop: function (event, ui) {
const usedListItem = ui.item;
const list = usedListItem.parent().children();
const orderedIds = [];
$.each(list, function () {
orderedIds.push($(this).attr('id'));
})
that.orderSortableListsInState(orderedIds);
}
});
}
orderSortableListsInState(orderedIds) {
// ... here you can sort the state of any list in your state tree
const orderedDetachedAttributes = this.orderListByIds(orderedIds, this.state.detachedAttributes);
if (orderedDetachedAttributes.length) {
this.state.detachedAttributes = orderedDetachedAttributes;
}
this.setState(this.state);
}
orderListByIds(ids, list) {
let orderedList = [];
for (let i = 0; i < ids.length; i++) {
let item = this.getItemById(ids[i], list);
if (typeof item === 'undefined') {
continue;
}
orderedList.push(item);
}
return orderedList;
}
getItemById(id, items) {
return items.find(item => (item.id === id));
}
// ... render etc.
}
The list element just needs an additional attribute for let jQuery select the element.
import React from 'react';
export default class Attributes extends React.Component {
render() {
const attributes = this.props.attributes.map((attribute, i) => {
return (<li key={attribute.id} id={attribute.id}>{attribute.name}</li>);
});
return (
<ul className="sortable">
{attributes}
</ul>
);
}
}
For ids i use UUID's so i havent conflicts when matching them in orderSortableListsInState().
You can use either useRef or the component id or class as usual...
import { useRef, useEffect } from 'react';
import $ from 'jquery';
import "jquery-ui-dist/jquery-ui"
export default function YourComponent() {
const ref = useRef()
useEffect(() => {
$(ref.current).sortable({
items: '>li',
});
}, []);
return (
<ul ref={ref}>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
)
}

jQuery UI Accordion - does refresh method overwrites initialisation settings?

Currently I am working on a project for which I use the jQuery UI Accordion.
Therefore I initialise the accordion on an element by doing
<div id="accordion"></div>
$('#accordion').accordion({
collapsible: true,
active: false,
heightStyle: "content"
});
After init the accordion I append some data coming from an AJAX request. (depends on user interaction)
In a simplified jsfiddle - which does exact the same thing as the ajax call - you can see how this looks like.
So far it seems to be working quite well but there is one problem I face.
In my initialisation I say that I want all panels to be closed but after calling refresh on the accordion everything of those settings seems to be gone and one panel opens.
Note that I implemented jQuery UI v1.10.2 in my fiddle. Update notes say
The refresh method will now recognize panels that have been added or removed. This brings accordion in line with tabs and other widgets that parse the markup to find changes.
Well it does but why has it to "overwrite" the settings I defined for this accordion?
I also thought about the possibility that it might be wrong to create the accordion on an empty <div> so I tested it with a given entry and added some elements afterwards.
But the jsfiddle shows exactly the same results.
In a recent SO thread I found someone who basically does the same thing as I do but in his jsfiddle he faces the same "issue".
He adds a new panel and the first panel opens after the refresh.
My current solution for this issue is to destroy the accordion and recreate it each time there's new content for it.
But this seems quite rough to me and I thought the refresh method solves the need to destroy the accordion each time new content gets applied.
See the last jsfiddle
$(document).ready(function () {
//variable to show "new" content gets appended correctly
var foo = 1;
$('#clickMe').on('click', function () {
var data = '';
for (var i = 0; i < 3; i++) {
data += '<h3>title' + foo + '</h3><div>content</div>';
foo++;
}
if ($('#accordion').hasClass('ui-accordion')) {
$('#accordion').accordion('destroy');
}
$('#accordion').empty().append(data).accordion({
collapsible: true,
active: false,
heightStyle: "content"
});
});
});
Unfortunately it is not an option for me to change the content of the given 3 entries because the amount of panels varies.
So my questions are the one in the title and if this behaviour is wanted like that or if anybody faces the same problem?
For the explanation of this behaviour, have a look in the refresh() method of the jquery-ui accordion widget, the problem you are facing is at line 10 :
refresh: function() {
var options = this.options;
this._processPanels();
// was collapsed or no panel
if ((options.active === false && options.collapsible === true) || !this.headers.length) {
options.active = false;
this.active = $();
// active false only when collapsible is true
} if (options.active === false) {
this._activate(0); // <-- YOUR PROBLEM IS HERE
// was active, but active panel is gone
} else if (this.active.length && !$.contains(this.element[0], this.active[0])) {
// all remaining panel are disabled
if (this.headers.length === this.headers.find(".ui-state-disabled").length) {
options.active = false;
this.active = $();
// activate previous panel
} else {
this._activate(Math.max(0, options.active - 1));
}
// was active, active panel still exists
} else {
// make sure active index is correct
options.active = this.headers.index(this.active);
}
this._destroyIcons();
this._refresh();
}

How do I process styles after a knockout computed method refreshes my view?

I have a problem in my KnockoutJS application that I can't seem to figure out. Basically, I've bound a list to a 'ko.computed' method which allows me to filter items from the main list. I use this list for my main display to the user. On each item in my template, I have one ore more buttons that I need to render as JqueryUI buttons. I can't seem to find the way to redraw the buttons correctly in my model once the computed triggers a change.
Here is a very (very) simple example of a mock view model:
function List(items) {
var self = this;
self.allItems = ko.observableArray(items || []);
self.search = ko.observable('');
self.filtered = ko.computed(function(){
var search = self.search();
return ko.utils.arrayFilter(self.allItems(), function(item){
return item == search;
});
});
}
My view might look like this:
Search: <input type='text' data-bind='value: search' />
<ul data-bind='foreach: filtered'>
<li>
<span data-bind='text: $data'> </span>
<button>NOTICE</button>
</li>
</ul>
And here is how I initialize the display:
$(function(){
var vm = new List(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
ko.applyBindings(vm);
$('button').button(); // <-- notice!
});
Note that everything works fine initially! I get the nice looking JqueryUI button when the page first displays... However, as soon as I enter a into the search box, the button loses it's style completely. I need to find a way to call $('button').button() again.
Is there an event or callback inside of Knockout.js that I could call to setup my ui buttons after the computed method is triggered?
Thanks in advance!
The reason the style is getting reset is because the dom element that the button was previously bound to has been destroyed.
You can solve this by creating a simple custom binding (not-tested)
ko.bindingHandlers.uibutton = {
init: function(element, valueAccessor) {
var $element = $(element), config = valueAccessor();
$element.button();
}
}
This can be added to your template with this addition
<button data-bind="uibutton: {}">NOTICE</button>
You can remove the call to $('button').button();
When using KO we can almost do without standard Jquery expressions altogether, often custom bindings allow us to do the same but with the possibility of more advanced things like reacting to observables etc.
Hope this helps

jQuery UI autocomplete select event not working with mouse click

I have a list of links, and I have this search box #reportname. When the user types in the search box, autocomplete will show the text of the links in a list.
<div class="inline">
<div class="span-10">
<label for="reportname">Report Name</label>
<input type="text" name="reportname" id="reportname" />
</div>
<div class="span-10 last">
<button type="button" id="reportfind">Select</button>
</div>
</div>
The user can then use the keyboard arrow to select one of the text, and when he press ENTER, browser will go to the address of the link. So far so good.
<script type="text/javascript">
$(document).ready(function () {
$("#reportname").autocomplete({
source: $.map($("a.large"), function (a) { return a.text }),
select: function () { $("#reportfind").click() }
})
$("#reportfind").click(function () {
var reportname = $("#reportname")[0].value
var thelinks = $('a.large:contains("' + reportname + '")').filter(
function (i) { return (this.text === reportname) })
window.location = thelinks[0].href
})
});
</script>
The issue is when the user types, autocomplete shows a list, and then the user use the mouse to click one of the result. With keyboard navigation, the content of the search box is changed, but if the user clicks one of the options, the search box is not modified and the select event is immediately triggered.
How can I make the script work with keyboard selection and mouse selection? How can I differentiate between select events that are triggered by keyboard with the ones triggered by mouse?
To your 2nd question: "How can I differentiate between select events that are triggered by keyboard with the ones triggered by mouse?"
The event object in the jQuery UI events would include a .originalEvent, the original event it wrapped. It could have been wrapped multiple times though, such as in the case of Autocomplete widget. So, you need to trace up the tree to get the original event object, then you can check for the event type:
$("#reportname").autocomplete({
select: function(event, ui) {
var origEvent = event;
while (origEvent.originalEvent !== undefined)
origEvent = origEvent.originalEvent;
if (origEvent.type == 'keydown')
$("#reportfind").click();
},
...
});
Thanks to #William Niu and firebug, I found that the select event parameter 'ui' contains the complete selected value: ui.item.value. So instead of depending on jquery UI to change the text of the textbox, which didn't happen if the user clicks with mouse, I just pick up the selected value from 'ui':
$("#reportname").autocomplete({
select: function (event, ui) {
var reportname = ui.item.value
var thelinks = $('a.large:contains("' + reportname + '")').filter(
function (i) { return (this.text === reportname) })
window.location = thelinks[0].href
};
})
I tested it in all version of IE (inlcuding 9) and always ended up with an empty input-control after I selected the item using the mouse. This caused some headaches. I even went down to the source code of jQuery UI to see what happens there but didn’t find any hints either.
We can do this by setting a timeout, which internally queues an event in the javascript-engine of IE. Because it is guaranteed, that this timeout-event will be queued after the focus event (this has already been triggered before by IE itself).
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
$this = $(this);
setTimeout(function () {
$('#txtBoxRole').val(value);
}, 1);
},
Had the same issue / problem.
Jquery: 1.11.1
UI: 1.11.0
Question: Do you use bassistance jquery validte plugin simultanously?
If positive: update this to a newest version or just disable it for tests.
I updated from 1.5.5 to 1.13.0
Helped for me. Good luck!
I recently encountered the exact same problem (autocomplete items not clickable, keyboard events working).
Turned out that in my case the answer was not at all JS related. The autocomplete UI was not clickable simply because it was lacking an appropriate value for the z-index CSS property.
.ui-autocomplete {
z-index: 99999; /* adjust this value */
}
That did the trick.
This may be a bit farshot, but I had a similar situation where selecting an autocomplete value left the input field empty. The answer was to ignore the "change" events (as those were handled by default) and replace them with binds to "autocompletechange" events.
The "change" event gets triggered before the value from autocomplete is in the field => the field had "empty" value when handling the normal "change" event.
// ignore the "change" event for the field
var item = $("#"+id); // JQuery for getting the element
item.bind("autocompletechange", function(event, ui) { [call your handler function here] }
I was facing a similar problem. I wanted to submit the form when the user clicked on an option. But the form got submitted even before the value of the input could be set. Hence on the server side the controller got a null value.
I solved it using a modified version of William Niu's answer.
Check this post - https://stackoverflow.com/a/19781850/1565521
I had the same issue, mouse click was not selecting the item which was clicked.My code was supposed to make an ajax call to fetch the data as per the selection item from autocomplete source.
Previous code: mouse click not working.
select: function(event, ui) {
event.preventDefault();
for(i= 0; i< customer.length; i++)
if(document.getElementById('inputBox').value == customer[i].name)
{
$.ajax({
call
})
Changed code :mouse click working
select: function(event, ui) {
// event.preventDefault();
for(i= 0; i< customer.length; i++)
// if(document.getElementById('inputBox').value == customer[i].fields.name)
if(ui.item.value == customer[i].name)
{
$.ajax({
call
})
After inspecting the code in the developer tools console, I noticed there were two list items added. I removed the pairing <li></li> from my response code and oh yeah, the links worked
I also added this function as the click event:
$("#main-search").result(function ()
{
$("#main-search").val("redirecting...."), window.location.href = $("#main-search").attr("href").match(/page=([0-9]+)/)[1];
})
This works and you can test it here: Search for the term dress -->

Resources