I'm tring to do a autocomplete from json url, it works good.
Now what I want, it's when I click to the autocomplete, I want to display the import button and if input is empty or we put a new value (not in the import), display the create button.
Give you a example on what i'm doing with some datas:
$('#search-deal').autocomplete({
source: function(request, response) {
var data =[{
"id": 1671,
"title": "Queens Park Tyres deal"
}, {
"id": 1672,
"title": "Wildman Craft Lager deal"
}, {
"id": 1673,
"title": "General Store deal"
}, {
"id": 1674,
"title": "Deluxe Off Licence deal"
}, {
"id": 1675,
"title": "Ahmed Halal Bazaar deal"
}];
var datamap = data.map(function(i) {
return {
label: i.id ' - ' i.title,
value: i.id ' - ' i.title,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
if(i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0){
document.getElementById("create").style.visibility = 'hidden';
document.getElementById("import").style.visibility = 'visible';
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
};
});
response(datamap);
},
minLength: 1,
delay: 100
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<input type="text" id="search-deal" />
<button id="create" type="submit" >Créer une affaire</button>
<button id="import" type="submit" style="visibility:hidden" >Importer</button>
The problem here, it's when I write "p", the button import show up and I want to show up only when I click to the autocomplete. The second problem, it's the button create nevere come back if value is empty or put another value
Anybody can help me ?
CodePudding user response:
I understand from the shared snippet that you are using jquery ui autocomplete
.
I would suggest following changes/updates to your code
- For changing button display on selecting the autocomplete item, use
select
event. https://api.jqueryui.com/autocomplete/#event-select - Whenever user types something, hide the import button. Display it only when an item is selected.
- For handling empty input case, use
oninput
event.
I have made following changes to the code you shared
- Added a new function to handle button toggle
- Hide the import button from
source
property i.e. when user type some input and also when input box is blank - Show the import button when user selects an autocomplete option
Working code link: https://plnkr.co/edit/PgzUuOADhIqk9zbl?preview
I hope this solves your issue