How to apply jQuery auto-complete in a Form-Set? - javascript

I'm stick at my thinking on how to apply a JS code to a form-set.
I've this HTML:
<input id="id_form-0-city" name="id_form-0-city" type="hidden">
<input id="id_form-0-city_input" name="id_form-0-city_input">
And I use this JS/jQuery code to auto-complete the #id_form-0-city_input input.
// Autocomplete stuff
$( "#id_form-0-city_input" ).autocomplete({ // mudar!!!!
source: function( request, response ) {
$.ajax({
url: "/internalapi/cidades/",
dataType: "json",
data: {
country: $('#id_country').find(":selected").val(),
term: request.term.toLowerCase()
},
success: function( data ) {
response($.map(data, function( item ) {
return {
label: item.name + " (" + item.zone + ", " + item.municipality + ")",
value: item.name,
id: item.id
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
var selectedObj = ui.item;
// Popular o campo id_city
$( "#id_form-0-city" ).val(selectedObj.id);
},
search: function(event, ui) {
$("#id_form-0-city_input").addClass( "ui-autocomplete-loading" ); // mudar!!!!!
},
open: function() {
$("#id_form-0-city_input").removeClass( "ui-autocomplete-loading" ); // mudar!!!!
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
The code above works great, but now I need to use this auto-complete code for this case:
<input id="id_form-0-city" name="id_form-0-city" type="hidden">
<input id="id_form-0-city_input" name="id_form-0-city_input">
<input id="id_form-1-city" name="id_form-0-city" type="hidden">
<input id="id_form-1-city_input" name="id_form-0-city_input">
<input id="id_form-2-city" name="id_form-0-city" type="hidden">
<input id="id_form-2-city_input" name="id_form-0-city_input">
<input id="id_form-3-city" name="id_form-0-city" type="hidden">
<input id="id_form-3-city_input" name="id_form-0-city_input">
<input id="id_form-4-city" name="id_form-0-city" type="hidden">
<input id="id_form-4-city_input" name="id_form-0-city_input">
...
...
The number of sets could be minimum 1 and maximum 10.
Can you give me some ideas to refactor the JS/jQuery code to work with formsets? A for loop is what I need to use?

You could add a rel element to your inputs if you don't want to use class, like:
<input id="id_form-0-city" name="id_form-0-city" type="hidden">
<input id="id_form-0-city_input" name="id_form-0-city_input" rel="autocomplete">
<input id="id_form-1-city" name="id_form-0-city" type="hidden">
<input id="id_form-1-city_input" name="id_form-0-city_input" rel="autocomplete">
<input id="id_form-2-city" name="id_form-0-city" type="hidden">
<input id="id_form-2-city_input" name="id_form-0-city_input" rel="autocomplete">
<input id="id_form-3-city" name="id_form-0-city" type="hidden">
<input id="id_form-3-city_input" name="id_form-0-city_input" rel="autocomplete">
<input id="id_form-4-city" name="id_form-0-city" type="hidden">
<input id="id_form-4-city_input" name="id_form-0-city_input" rel="autocomplete">
And then just add the autocomplete logic inside this
$("input[rel='autocomplete']").autocomplete({ // mudar!!!!
...

Just use a for loop...
var inputLength = $('input:not(input[type="hidden"])').length; //find non-hidden inputs
for(var a = 0; a<inputLength; a++){
// Autocomplete stuff
$( "#id_form-" + a + "-city_input" ).autocomplete({ // mudar!!!!
source: function( request, response ) {
$.ajax({
url: "/internalapi/cidades/",
dataType: "json",
data: {
country: $('#id_country').find(":selected").val(),
term: request.term.toLowerCase()
},
success: function( data ) {
response($.map(data, function( item ) {
return {
label: item.name + " (" + item.zone + ", " + item.municipality + ")",
value: item.name,
id: item.id
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
var selectedObj = ui.item;
// Popular o campo id_city
$( "#id_form-" + a + "-city" ).val(selectedObj.id);
},
search: function(event, ui) {
$("#id_form-" + a + "-city_input").addClass( "ui-autocomplete-loading" ); // mudar!!!!!
},
open: function() {
$("#id_form-" + a + "-city_input").removeClass( "ui-autocomplete-loading" ); // mudar!!!!
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
}
DEMO:
http://jsfiddle.net/NcTpj/10/

Related

ui-autocomplete showing all results instead of filtered results

I'm just trying something out, as an experiment, with the jQuery autocomplete widget.
I used this as an example: Autocomplete | APi Data
But when i try it, it's not filtering the results. it only shows all results when i type something and then 'backspace-it-all'
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "https://nyros-ecommerce.myshopify.com/products.json",
dataType: "json",
dataFilter: function (data) { return data; },
success: function( data ) {
console.log(data)
response( $.map( data.products, function( result ) {
return {
value: result.handle,
imgsrc: result.images[0].src
}
}));
}
});
},
minLength: 1,
select : function(event, ui) {
event.preventDefault();
window.location.href = "/products/"+ui.item.value;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
console.log(item.value)
return $( "<li></li>" )
.data( "item.ui-autocomplete", item.value )
.append( "<a>" + "<img style='width:50px;height:55px' src='" + item.imgsrc + "' /> " + item.label+ "</a>" )
.appendTo( ul );
};
});
</script>
<div class="ui">
<label for="name">producst search: </label>
<input id="name">
</div>
The only issue with your code is, you are fetching data in function but not filtering the data.
You just need to filter your data using the following line. Here final_data is nothing but your resulted output.
response($.ui.autocomplete.filter(final_data, request.term));
Try below code.
$(function() {
$( "#name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "https://nyros-ecommerce.myshopify.com/products.json",
dataType: "json",
dataFilter: function (data) { return data; },
success: function( data ) {
var final_data =( $.map( data.products, function( result ) {
return {
value: result.handle,
imgsrc: result.images[0].src
}
}));
response($.ui.autocomplete.filter(final_data, request.term));
}
});
},
minLength: 1,
select : function(event, ui) {
event.preventDefault();
window.location.href = "/products/"+ui.item.value;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.ui-autocomplete", item.value )
.append( "<a>" + "<img style='width:50px;height:55px' src='" + item.imgsrc + "' /> " + item.label+ "</a>" )
.appendTo( ul );
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<div class="ui">
<label for="name">producst search: </label>
<input id="name">
</div>

jQuery UI Autocomplete value not appear properly in selection

My sources are JSON objects that fetched from url and it looks like below.
[
{"ID":1,"GROUP_ID":"1","CONTACTNAME":"Mizuki","PHONENUMBER":"+6289695049930"},
{"ID":15,"GROUP_ID":"3","CONTACTNAME":"Sinbad","PHONENUMBER":"+6287654321"},
{"ID":23,"GROUP_ID":"","CONTACTNAME":"Titus","PHONENUMBER":"+6255555555"}
];
When user typing, result of suggestion is CONTACTNAME and value that inserted into searchbox is PHONENUMBER. Fetch data from source/url have no issue but in searchbox there's no value passed.
Screenshot below
Here's my script
$(function() {
$( "#contact" ).autocomplete({
source: "api/contact/auto",
minLength: 1,
focus: function( event, ui ) {
$("#contact").val(ui.item.CONTACTNAME);
return false;
},
select: function( event, ui ) {
$("#contact").val(ui.item.PHONENUMBER);
return false;
}
});
});
Form view
<input type="text" v-model="message.DESTINATIONNUMBER" id="tags" class="form-control" name="destinationNumber" >
I try to remove vue snippet (v-model) still same.
Any suggestion? Whats wrong?
UPDATED!!
My mistake. Forgot add this code at the end.
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
So, full javascript is like in jquery-ui docs
$(function() {
$( "#contact" ).autocomplete({
source: "api/contact/auto",
minLength: 1,
focus: function( event, ui ) {
$("#contact").val(ui.item.CONTACTNAME);
return false;
},
select: function( event, ui ) {
$("#contact").val(ui.item.PHONENUMBER);
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
Thanks for people who try to help me. Appreciate it.
For the autocomplete to work, you need to have "label" attribute in the returned JSON array. You can either change that on the server side, or transform it on the client as follows:
$( "#contact" ).autocomplete({
source: function (request, response) {
$.ajax({
url: "api/contact/auto",
data: { query: request.term },
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el.CONTACTNAME,
value: el.PHONENUMBER,
id: el.ID
};
});
response(transformed);
},
error: function () {
response([]);
}
});
});
minLength: 1,
focus: function( event, ui ) {
$("#contact").val(ui.item.CONTACTNAME);
return false;
},
select: function( event, ui ) {
$("#contact").val(ui.item.PHONENUMBER);
return false;
}
});
There were a couple of errors in your JavaScript:
"source" is misspelled ("sorGce")
in availableTags indexes except 0, the colon is inside the quotes instead of outside
Working fiddle:
sorGce: availableTags, -> source: availableTags,
"ID:" "23", -> "ID": "23",
https://jsfiddle.net/ep1s9w3s/1/
Not sure if this is the root cause of your problem or not, but it might help you fix your fiddle.

Jquery ui autocomplete not fill

I'm new to JQuery and jQuery UI.
I'm using autocomplete with remote json in a table with dynamically rows.
The problem is: everything works, but for some reasons, the input code isn't filled.
The curious thing is that if I hardcode #code0 or #code1 in select area, it works.
But it seem #code+i isn't recognized in select. Another strange thing is $("#product"+i) works.
Can someone help a JS beginner?
$(document).ready(function(){
var i=0;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"<\/td><td><input id='product"+i+"' name='product"+i+"' type='text' placeholder='Digita il codice o il nome del prodotto' class='form-control input-md' /> <\/td><td><input id='code"+i+"' name='code"+i+"' type='text' placeholder='Codice' class='form-control' readonly='readonly'><\/td>");
$('#tab_logic').append('<tr id="addr'+(i+1)+'"><\/tr>');
$("#product"+i).autocomplete({
source: function( request, response ) {
$.ajax({
url: "productsearch.php",
dataType: "json",
data: {term: request.term},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.text,
id: item.id,
code: item.id
};
}));
}
});
},
minLength: 2,
select: function(event, ui) {
var codice="$code"+i;
$('#codice').val(ui.item.id);
}
});
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
$("#product"+i).autocomplete({
source: function( request, response ) {
$.ajax({
url: "productsearch.php",
dataType: "json",
data: {term: request.term},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.text,
id: item.id,
code: item.id
};
}));
}
});
},
minLength: 2,
select: function(event, ui) {
$("#code"+i).val(ui.item.id);
}
});
i++;
});
});
<tbody>
<tr id='addr0'>
<td>1</td>
<td><input id="product0" type="text" name='product0' placeholder='Digita il codice o il nome del prodotto' class="form-control"></td>
<td><input id="code0" type="text" name='code0' placeholder='Codice' class="form-control" readonly="readonly"></td>
</tr>
<tr id='addr1'>
</tr>
One thing for sure is that in your select event handler on the first autocomplete, you have a bug:
select: function(event, ui) {
var codice="$code"+i;
$('#codice').val(ui.item.id);
}
You create a variable for the jquery selector and then don't use it. You can't update your input value whose id is "code"+i with this function. Instead, it needs to be:
select: function(event, ui) {
var codice="#code"+i;
$(codice).val(ui.item.id);
}
Fix that and see if your problem goes away.
I've solved by adding a new var count=0; at the top.
Now I use:
$("[id^=code]:eq( " + count + " ) ").val(ui.item.id);
the problem is the variable i
Thank you everyone for the help
select: function(event, ui) {
$("[id^=code]:eq( " + count + " ) ").val(ui.item.id);
}
});
i++;
count++;
});

jquery functions within modal only work on first open, after close and re-open they stop working

I am using jquery modal, within each modal I have a form. I am then loading certain jquery functions onto the form elements, for example jquery autocomplete.
When I open the modal for the first time it is working fine with all the jquery functions within the script, but as soon as I close the first modal and open again none of the functions work.
Its as though they are binded on the page load to the form, then when the button is clicked for the modal its works and then closing the modal unbinds it.
Does anybody have any ideas as to why they would stop working after the first modal open/close?
$(document).ready(dialogForms);
function dialogForms() {
$('a.menubutton').click(function() {
var a = $(this);
$.get(a.attr('href'),function(resp){
var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
$('body').append(dialog);
dialog.find(':submit').hide();
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {
if($(this).find('form').valid()){
// do stuff if form validates
submitFormWithAjax($(this).find('form'));
$('#homepage').trigger('click');
$(this).dialog('close');
}
else {
}
},
'Cancel': function() {$(this).dialog('close');}
},
width: 650,
height: 400,
show: "fade",
hide: "fade"
});
$('#edit_vle').bind('change', function (e) {
if( $('#edit_vle').val() == 'FE') {
$('#fe_automcomplete1').show();
$('#he_automcomplete1').hide();
$("#edit_he_title").val("");
$("#edit_he_code").val("");
}
else{
$('#fe_automcomplete1').hide();
$('#he_automcomplete1').show();
$("#edit_fe_title").val("");
$("#edit_fe_code").val("");
}
});
$('#delete_vle').bind('change', function (e) {
if( $('#delete_vle').val() == 'FE') {
$('#fe_automcomplete2').show();
$('#he_automcomplete2').hide();
$("#delete_he_title").val("");
$("#delete_he_code").val("");
}
else{
$('#fe_automcomplete2').hide();
$('#he_automcomplete2').show();
$("#delete_fe_title").val("");
$("#delete_fe_code").val("");
}
});
var epronames = [<?php
$eprotmp = Array();
while($eprorow = mssql_fetch_array($epro_course)) $eprotmp[] =
'{
title: "'.$eprorow['Name'].'",
label: "'.$eprorow['Code'].' - '.$eprorow['Name'].'",
code: "'.$eprorow['Code'].'",
user: "'.$eprorow['fname'].' '.$eprorow['sname'].'",
}';
echo join(',', $eprotmp);
?>];
var fenames = [<?php
$fetmp = Array();
while($ferow = mysql_fetch_array($feinactive)) $fetmp[] =
'{
title: "'.$ferow['course'].'",
label: "'.$ferow['shortname'].' - '.$ferow['course'].'",
code: "'.$ferow['shortname'].'",
}';
echo join(',', $fetmp);
?>];
var henames = [<?php
$hetmp = Array();
while($herow = mysql_fetch_array($heinactive)) $hetmp[] =
'{
title: "'.$herow['course'].'",
label: "'.$herow['shortname'].' - '.$herow['course'].'",
code: "'.$herow['shortname'].'",
}';
echo join(',', $hetmp);
?>];
$("#title").autocomplete({
minLength: 3,
source: epronames,
focus: function( event, ui ) {
$("#title").val( ui.item.label );
return false;
},
select: function( event, ui ) {
$("#title").val( ui.item.title );
$("#code").val( ui.item.code );
$("#ctl").val( ui.item.user );
return false;
},
change: function(event, ui) {
if (!ui.item) {
$("#title").val("");
}
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$("#edit_he_title").autocomplete({
minLength: 3,
source: henames,
focus: function( event, ui ) {
$("#edit_he_title").val( ui.item.label );
return false;
},
select: function( event, ui ) {
$("#edit_he_title").val( ui.item.title );
$("#edit_he_code").val( ui.item.code );
return false;
},
change: function(event, ui) {
if (!ui.item) {
$("#edit_he_title").val("");
}
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$("#edit_fe_title").autocomplete({
minLength: 3,
source: fenames,
focus: function( event, ui ) {
$("#edit_fe_title").val( ui.item.label );
return false;
},
select: function( event, ui ) {
$("#edit_fe_title").val( ui.item.title );
$("#edit_fe_code").val( ui.item.code );
return false;
},
change: function(event, ui) {
if (!ui.item) {
$("#edit_fe_title").val("");
}
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
if($("#clearform").length > 0){
$("#clearform").click(function() {
$("#title").val('');
$("#code").val('');
$("#ctl").val('');
});
}
if($("#delete_fe_clearform").length > 0){
$("#delete_fe_clearform").click(function() {
$("#delete_fe_title").val('');
$("#delete_fe_code").val('');
});
}
if($("#edit_fe_clearform").length > 0){
$("#edit_fe_clearform").click(function() {
$("#edit_fe_title").val('');
$("#edit_fe_code").val('');
});
}
if($("#delete_he_clearform").length > 0){
$("#delete_he_clearform").click(function() {
$("#delete_he_title").val('');
$("#delete_he_code").val('');
});
}
if($("#edit_he_clearform").length > 0){
$("#edit_he_clearform").click(function() {
$("#edit_he_title").val('');
$("#edit_he_code").val('');
});
}
}, 'html');
return false;
});
}
function submitFormWithAjax(form) {
form = $(form);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method')),
dataType: 'script',
success: function(data){
}
});
return false;
}
Here are the buttons for each modal.
New Course
Edit Course
Delete Course
I placed the jquery functions into the open method
open: function(){
To close the dialog instead of using:
$(this).dialog('close');
I used
dialog.remove();
My functions now work every time i open the dialog

Using jQuery-ui autocomplete variables in further jQuery-ui autocomplete functions

How can I use the selected item from a jQuery-ui autocomplete in a further jQuery-ui autocomplete function?
e.g. for this HTML:
<div class="ui-widget">
<label for="project">Project: </label>
<input id="project" />
<label for="phase">Phase: </label>
<input id="phase" />
<label for="filename">Project: </label>
<input id="filename" />
</div>
I am using the following autocomplete function with a JSON endpoint to supply the data.
$(function() {
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2,
select: function( event, ui ) {
}
});
});
Then in this second autocomplete I want to take the selected value from the first autocomplete function and use it to build the URL string for use in the source attribute of a second autocomplete (shown here as valueFromFirstAutocomplete).
$(function() {
$( "#phase" ).autocomplete({
source: baseUrl+"json/listphases/"+valueFromFirstAutocomplete,
minLength: 2,
select: function( event, ui ) {
}
});
});
Customize the source option with a callback, adding the additonal parameter to the URL:
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2
});
$( "#phase" ).autocomplete({
source: function(request, response) {
$.get(baseUrl + "/json/listphases/" + $("#project").val(), request, response);
},
minLength: 2
});
You could just put one inside the other....
Is there some reason this won't work?
$(function() {
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2,
select: function( event, ui ) {
$(function() {
$( "#phase" ).autocomplete({
source: baseUrl+"json/listphases/"+ui.item.value,
minLength: 2,
select: function( event, ui ) {
}
});
});
}
});
});
To use these independently you could do something like this:
var funclist = {
populate1 : function() {
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2,
select: populate2;
},
populate2 : function(event,ui) {
$( "#phase" ).autocomplete({
source: baseUrl+"json/listphases/"+ui.item.value,
minLength: 2,
select: populate3;
}
populate3 : ; // etc
}
$(funclist.populate1);

Categories