jQuery mobile autocomplete is not updating itself - jquery-mobile

I'm new to jQuery and jQuery mobile.
I'm trying to get an autocomplete field working. What I have so far is pretty much ripped right from the demo at http://demos.jquerymobile.com/1.4.5/listview-autocomplete-remote/
$( document ).on( "pagecreate", "#foo", function() {
$( "#autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class=\'ui-loader\'><span class=\'ui-icon ui-icon-loading\'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "/cgi/perl_script.pl",
data: \'search=\' + value,
dataType: "json",
traditional: true
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
alert(JSON.stringify(val));
html += "<li>Just a test</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
I have confirmed that json data is getting returned with the js alert. That's all working perferctly. If my perl script returns 3 json records, I get three alerts with the stringified JSON.
However, the records never get displayed by the widget even if I use a the simple "Just a test" string as shown here in my code as I try to debug the problem.
Here is the relevant html code:
<div role="main" class="ui-content">
<form class="ui-filterable">
<input id="autocomplete-input" data-type="search" placeholder="Last name">
</form>
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-input="#autocomplete-input"></ul>

See comments to the original post for the answer.

Related

jquery_ui menu ui parameter for dynamic sub-menu

I am trying to create a dynamic sub-menu. For example, the top-level items are load and edit. Whenever the menu is focused, a get JSON is called and the result used to populate the possible items to load under the load menu item. However, the ui parameter for the select event handler no longer seems to correspond to the item clicked and calling ui.item.text() will instead return the entire text to the sub-menu.
HTML:
...
<ul id="menu">
<li><div>load</div><ul id="load"></ul></li>
<li><div>edit</div></li>
</ul>
...
javascript:
var load_populate = function ( json ) {
var ul = $( "#load" );
ul.empty();
for ( let item of json ) {
ul.append ( $( "<li>" ).append ( $( "<div>" ).text ( item.name ) ) );
}
};
var menu_focus = function ( event, ui ) {
$.getJSON ( load_options_url )
.done ( load_populate );
};
var menu_select = function ( event, ui ) {
console.log ( ui.item.text() );
};
$( "#menu" ).menu ({
"focus" : menu_focus,
"select" : menu_select
});
Clicking an item in the load sub-menu logs
loaditem1item2item3, etc.
Refreshing the menu did not work.
How do I go about this?
Here is an example based on your code.
Example Fiddle
This uses POST just to simulate the AJAX activity
https://jsfiddle.net/Twisty/qpky9ht1/53/
HTML
<ul id="menu">
<li>
<div>load</div>
<ul id="load">
</ul>
</li>
<li>
<div>edit</div>
</li>
</ul>
JavaScript
Adjusted to be more similar to your code.
$(function() {
function makeListItem(o, n) {
$(o).append("<li><div>" + n + "</div></li>");
}
$("#menu").menu({
focus: function(e, ui) {
console.log("FOCUS", e, ui.item);
if (ui.item.parent().is("#menu")) {
$.getJSON (load_options_url,
function(json) {
console.log("LOAD");
$("#load").empty();
$.each(json, function(i, m) {
console.log("ITEM", i, m);
makeListItem("#load", m.name);
});
$("#menu").menu("refresh");
});
}
},
select: function(e, ui) {
console.log("SELECT", ui.item);
}
});
});
This will gather the list data in focus and append them. Once this is done, refresh method is executed on the Menu. This will assimilate all the new list items into the menu. Since focus can be executed on all menu items, you want to ensure you are not rebuilding the menu while focusing on sub-menu items. Hence the if statement.

jquery mobile data-lastval

I need help with an Intel XDK project.
After research I was succesfull to create an autocomplete form.
However, if the user do not select the value from filter list,
and enter the value manually, it is not saved to the variable.
It would be possible to select the value in "data-lastval".
Here is the code that appears in DOM. But with all the research I do, I cannot understand, how to fetch this content of data-lastval and put in into a variable. On selection of the list item it goes saved to a hidden input field and can be stored to localstorage. I need help in building this javascript or jquery mobile selector, like var xstreet = ...
"If"-logic will decide, that the hidden field was empty, and then put "xstreet" instead in this.
<div class="ui-input-search ui-shadow-inset ui-input-has-clear ui-body-e ui-corner-all">
<input data-type="search" placeholder="street" data-lastval="2323">
Clear text</div>
Code in src:
<div class="widget uib_w_15 form1widths labelwhite form1forms streetfield" data-uib="jquery_mobile/input" data-ver="0" id="streetfield"><input type="hidden" id="xd">
<ul class="autocomplete" data-role="listview" data-inset="true" data-filter="true"
data-filter-placeholder="street" data-filter-theme="e"></ul>
</div>
Code in the head:
<script>
$('#streetfield ul').listview();
var gcity = window.localStorage.getItem("city");
$(document).on( "pageinit", "#form", function() {
$(".autocomplete").on("listviewbeforefilter", function(e, data ) {
var $ul=$(this);
var value = $( data.input ).val();
var dropdownContent = "" ;
$ul.html("") ;
if ( value && value.length > 2 ) {
var response = ['data1','data2','data3'];
$('.autocomplete').show();
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading' ></span></div></li>" );
$ul.listview( "refresh" );
$.each(response, function( index, val ) {
dropdownContent += "<li>" + val + "</li>";
$ul.html( dropdownContent );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
$(document).on( "click", ".autocomplete li", function() {
var selectedItem = $(this).html();
$(this).parent().parent().find('input').val(selectedItem);
$('.autocomplete').hide();
});
</script>
Well, nobody helped. I think, this may be the solution.
I found it in an other case.
var x = $(#id).attr('data-lastval')
maybe it can help somebody.

Using Handlerbars with Yahoo Pipes

I'm trying to pull JSON feeds from a yahoo pipes source into my jQuery Mobile project using Handlebars.js with jQuery's ajax method.
This method works without Handlebars, but there are some limitations. It doesn't show up in jquerymobile listview format, instead it pops out like a normal bullet list. Here's the source:
var pipeURL = "http://pipes.yahoo.com/pipes/pipe.run?_id=mu3NkfY_3BGtncSIJhOy0Q&_render=json";
$.ajax({
url : pipeURL,
dataType : "json",
success : function(data) {
console.log(data);
var html = '<ul data-role="listview" id="all-posts-two" data-filter="" data-count-theme="c">';
$.each(data.value.items, function(i, item) {
html += "<li>" + item.title + "</li>";
});
html += "</ul>";
//Add the feed to the page
$("#PostsList").empty().html(html);
}
});
Here's the source for the other method I've been trying to use with Handlebars but obviously I'm missing something somewhere.
$.ajax({
url : pipeURL,
dataType : "json",
success : function(data) {
//line to check the received data on the console
console.log(data);
//handlebars area
var source = $("#posts-template").html();
var template = Handlebars.compile(source);
var blogData = template(data);
$("#all-posts").append(blogData);
$("#all-posts").trigger("create");
dfd.resolve(data);
},
error : function(data) {
// console.log(data);
}
});
Here's the html source for the template
<ul data-role="listview" id="all-posts" data-filter=""></ul>
<script id="posts-template" type="text/x-handlebars-template">
{{#each value.items}}
<li data-postid="{{ID}}">
<a data-transition="slide" href="#">
<p>{{{title}}}</p>
</a>
</li>
{{/each}}
</script>
Anyone, please help me out please
From what I can see you are using an older version of jQuery Mobile (lower then 1.4).
Do it like this:
var pipeURL = "http://pipes.yahoo.com/pipes/pipe.run?_id=mu3NkfY_3BGtncSIJhOy0Q&_render=json";
$.ajax({
url : pipeURL,
dataType : "json",
success : function(data) {
console.log(data);
var html = '<ul data-role="listview" id="all-posts-two" data-filter="" data-count-theme="c">';
$.each(data.value.items, function(i, item) {
html += "<li>" + item.title + "</li>";
});
html += "</ul>";
//Add the feed to the page
$("#PostsList").empty().html(html);
$('#all-posts-two').listview('refresh');
}
});
Look at this line:
$('#all-posts-two').listview('refresh');
It will enhance dynamically added listview, of course there's one more thing, you need need to trigger it after whole dynamic list has been done and not on every li element, it will fail in this case. In your next example you are using this line:
$("#all-posts").trigger("create");
It will fail because trigger('create') is used to enhance whole data-role="content" not just part of it so as such it should be used only on data-role="content" div.
Read more about it in this other answer.
Or take a look at my blog article, there you will find a working example of listview created from remote JSON data.
Update:
If you are using jQuery Mobile 1.4 try this line:
$('#all-posts-two').enhanceWithin();
.enhanceWithin() is method introduced in jQuery Mobile 1.4 to replace all other methods.
Update 2
This question is finally answered in another question, or you can find it here with working example:

refresh div in jquerymobile v1.3.2 ,phonegap v2.9.0

I'm working in jquerymobile v1.3.2,Phonegap 2.9.0
i am getting photos from ajax webservice which is working fine. Now want to implement lightbox I get photos from ajax and concatenate in div. Here is my code. I have used this photo lightbox from jquerymobile demo help.
//var contenttype;
//var cookies;
//var aGallery;
var ItemsCount=photolink_arr.length;
var divGallery = document.getElementById("Gallery");
for (var i=0; i < ItemsCount; i++)
{
$.ajax({
type: 'get',
async: false,
url: photolink_arr[i],
dataType: "json",
contentType: contenttype,
headers: {Cookie: cookies},
success: function (data){
var photo= data.image_link;
var thumbphoto= data.thumbnail_link;
aGallery += ' <img class="popphoto" src="' + thumbphoto + '" alt="Photos" style="width:30%">';
aGallery += ' <div data-role="popup" id="popupPhoto' + i + '" data-overlay-theme="a" data-theme="d" data-corners="false">';
aGallery += ' Close<img class="popphoto" src="' + photo + '" style="max-height:512px;" alt="Paris, France"> </div>';
divGallery.innerHTML = aGallery;
},
complete: function() {
console.log ('LoadphotosView function complete');
},
error: function (request,data)
{
alert("load albums error request=" + JSON.stringify( request));
}
}) ;
}
html
<div id="ViewPhotopage" data-role="page" class="RedScreen">
<script type="application/javascript" src="js/AlbumCategory.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", function() {
console.log('Photo view device ready started');
tabBar.hide();
});
$(document).ready(function(){
console.log('albums category document ready');
LoadAlbums();
});
$( document ).on( "pageinit", function() {
$( ".photopopup" ).on({
popupbeforeposition: function() {
var maxHeight = $( window ).height() - 60 + "px";
$( ".photopopup img" ).css( "max-height", maxHeight );
}
});
});
</script>
<div id="Header" data-role="header">
<a data-rel="back" data-role="button" data-inline="true" data-theme="b">Back</a>
<h1>Photo View</h1>
<a rel="external" data-role="button" href="PhotoAdd.html" data-inline="true" data-theme="b">Add</a>
</div>
<div id="Gallery" data-role="content" class="gallery">
<div style='font-size:14pt;color:#fff;'>Loading..</div>
</div>
</div>
the images and popups both are shown hyper link is also not working. i only want to show thumbnail and on click large image should be shown in lightbox. i think i have to refresh div just as listview in jquerymobile.I have worked with photoswipe and the problem is same.Do you suggest anything or give Any alternative.

Jquery ui - Autocomplete - Change Label of Field while keeping the same post value

im working on this jquery data entry form in which i need a specific field to be autocompleted with data from mysql
i got everything working, autocomplete retrieves data from the sql through php matching is great in english/latin and utf8 characters
the values get retrieved from the sql as "'number' => 'name'"
right now the autocomplete has 3 values in the output, value, label and id.
as id and value it uses the 'name'
and the label is the 'number' of my sql string (which is posted to the next page when the form is submited)
so everyting works ok, my 'number' is posted correctly, there is a minor annoyance tho
when i select something from the autocomplete list, the field is populated with the 'number'
is there any way to fill it with the 'name'?
ie: search for 'name', get dropdown with 'names', click and get the 'name' in the field, and when i submit i get the 'number' posted?
any help would be greatly appreciated.
if you need to take a look at my code, it's posted on a previous question: Jquery ui - Autocomplete - UTF8 charset
thanx in advance :)
The usual way to do this is:
Use a hidden input to hold the value you'd like to POST, then autocomplete a separate field.
Populate the hidden input on select
Populate the visible, autocompleted input with the label property of the item that was selected.
So, for example:
HTML:
<input type="hidden" name="name" />
<input type="text" id="name_auto" />
JavaScript:
$(function () {
var cache = {},
lastXhr;
$( ".name" ).autocomplete({
minLength: 1,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
},
select: function (event, ui) {
event.preventDefault();
this.value = ui.item.label;
},
change: function (event, ui) {
if (ui.item) {
$("input[name='name']").val(ui.item.value);
} else {
$("input[name='name']").val('');
}
}
});
});
You can use the result (handler) from u'r autocomplete
where the variable data such as arrays and you can return two data at once
Expl:
in javascript
$().ready(function()
{
var url = "<?=base_url()?>index.php/master/agen";
var width_val = 308;
$("#name_auto").autocomplete(url,
{
width: width_val,
selectFirst: false,
});
$("name_auto").result(function(event, data, format)
{
$("#name_auto").val(data[0]);
$("#id").val(data[1]);
});
});
in HTML :
<input type="hidden" name="number" id="id" />
<input type="text" id="name_auto" name="name" />
in PHP :
foreach ($source->result() as $row)
{
echo "$row->nama|$row->id\n";
}
note : here I use PHP CodeIgniter in its

Resources