I have code written to autocomplete a text input box from a mysql database. I am currently in the process of mitigating the setup to jQuery Mobile but I am having substantial issues finding out how to write a modified autocomplete. My original html is below (heavily simplified)
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<script>
$(function() {
$( "#get_ingredient_1" ).autocomplete({source: 'search.php'});
});
</script>
<div class="ui-widget">
<input id="get_ingredient_1" name="ingredient_type" style = "width:200px">
</div>
</html>
the search.php is shown below.
<?php
//database configuration
include("db_connect.php");
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$category_query = mysqli_query($dbconnection, "SELECT DISTINCT ingredient FROM ingredients WHERE ingredient LIKE '%".$searchTerm."%' ORDER BY ingredient ASC");
//while ($row = $query->fetch_assoc()) {
while($row = mysqli_fetch_assoc($category_query)){
$data[] = $row['ingredient'];
}
//return json data
echo json_encode($data);
?>
this outputs in the format:
["Adzuki beans","Alfalfa","Allspice","Almond meal"]
ive tried to comment it accordingly. Essentially this generates a text input bot and when you start typing will try and guess what ingredient you are wanting.
unfortunatly when I alter the jquery files to:
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
It no longer autocompletes. Ive read through dozens of examples but I cant find a basic 1 input autocomplete option that I can adapt.
Can anyone shed some light on how to alter this short piece of code to autocomplete, so I can study and adapt it to its full functionality.
Ive looked at all the jquery-mobile examples but have found them lacking in the details I need here, specifically the "remote listview" as it has to populate from a file generated from a mysql source like the search.php shown above.
hope someone can help translate this to jquery mobile use.
Related
I am fairly new to both MVC and JQGrid. I am having an issue with getting AutoComplete or DatePicker to work with either editing or searching.
I'm assuming (hoping) that one solution will fix both issues since I am getting a similar error for both, so for the time being I've stripped it down to just AutoComlete to simplify things.
I've been following the example at http://www.trirand.net/aspnetmvc/grid/performancelinqsearch
to get AutoComplete to work in the search toolbar above the columns.
It seems that no matter what I try, AutoComplete doesn't work and I get this error in Chrome's dev console: "Uncaught ReferenceError: AutoComplete_acid is not define".
Here is my view. I've disabled the master layout in case that was causing any conflicts. I have tried using the version of jQuery that came with the jqGrid download instead of the latest. I'm not getting the alert about AutoComplete missing or a Failed to load resource that happens when I exclude the AutoComplete script.
#model MRA_Survey_Manager.Models.ESLogModel
#using Trirand.Web.Mvc
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>MRA Survey Manager</title>
<link rel="stylesheet" type="text/css" href="~/Content/themes/base/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="~/Content/jquery.jqGrid/ui.jqgrid.css" />
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="~/Scripts/jqGrid/i18n/grid.locale-en.js"></script>
<script type="text/javascript" src="~/Scripts/jqGrid/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="~/Scripts/jqGrid/jquery.jqAutoComplete.min.js"></script>
<script type="text/javascript" src="~/Scripts/jqGrid/CustomValidators.js"></script>
</head>
<body>
<div style="Width:100%">
#Html.Trirand().JQGrid(Model.ESLogGrid, "ESLogGrid")
#{
Html.Trirand().JQAutoComplete(
new JQAutoComplete
{
DisplayMode = AutoCompleteDisplayMode.ControlEditor,
DataField = "Carrier",
DataUrl = Url.Action("AutoCompleteCarrier", "ESLogGrid")
}, "AutoComplete");
}
</div>
</body>
</html>
And in my controller I have:
public JsonResult AutoCompleteCarrier(string term)
{
JQAutoComplete autoComp = new JQAutoComplete();
autoComp.DataField = "Carrier";
autoComp.AutoCompleteMode = AutoCompleteMode.BeginsWith;
autoComp.DataSource = from survey in db.MRA_SurveyLog
select survey;
return autoComp.DataBind();
}
And within my grid setup:
JQGridColumn column = logGrid.Columns.Find(c => c.DataField == "Carrier");
column.SearchType = SearchType.AutoComplete;
column.Searchable = true;
column.DataType = typeof(string);
column.SearchControlID = "AutoComplete";
column.SearchToolBarOperation = SearchOperation.BeginsWith;
I have checked the three things listed at http://www.trirand.net/forum/default.aspx?g=posts&t=2902
I have been struggling with this for quite a while. Any help would be greatly appreciated.
I finally figured it out. It turned out to be an issue with the Razor syntax in the view. For some reason defining the AutoComplete object in a multi-statement block caused that error.
Changing it to a single-statement fixed the issue.
#Html.Trirand().JQAutoComplete(new JQAutoComplete{DisplayMode = AutoCompleteDisplayMode.ControlEditor, DataField = "Carrier", DataUrl = Url.Action("AutoCompleteCarrier", "ESLogGrid")}, "AutoComplete")
Edit: After resolving another recent issue I've had with Razor syntax I wanted to come back and update this solution. The issue was with my understanding of the syntax and not jqGrid itself. When you have curly braces within a multi-statement block you apparently have to wrap that section in text tags. So the following should also work:
#{
<text>
#Html.Trirand().JQAutoComplete(
new JQAutoComplete
{
DisplayMode = AutoCompleteDisplayMode.ControlEditor,
DataField = "Carrier",
DataUrl = Url.Action("AutoCompleteCarrier", "ESLogGrid")
}, "AutoComplete")
</text>
}
More Information at: https://stackoverflow.com/a/6099659/1451531
I see some others (e.g. this post) have had trouble using external javascript scripts in JQuery Mobile - as of today I have joined their ranks.
I have a single external js script (controllers.js) which contains code that affects several pages on the site. It is loaded on every page of the site. I put the js file just before the tag it works fine on the initial page load. However when I navigate thereafter (using the JQM Ajax methods) all functions in the script stop working. I would have thought the script would remain in cache - but heyho. Anyhow there's an FAQ which answers this question and I've implemented their suggestion which is: "...to reference the same set of stylesheets and scripts in the head of every page." I have done this but when I do even on the first page load the js doesn't fire. There aren't page specific scripts - so the remainder of that FAQ does not apply.
My cut down html looks like this:
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" href="/static/jquery-ui-1.10.3.custom.min.css">
<link rel="stylesheet" href="/static/jquery-mobile/css/themes/default/jquery.mobile-1.3.2.min.css">
<script src="/static/jquery-1.9.1.min.js"></script>
<script src="/static/jquery-ui/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>
<script src="/static/jquery-mobile/js/jquery.mobile-1.3.2.min.js"></script>
<!-- CSS: implied media="all" -->
</head>
<body>
<div data-role="page" id = "main-page">
<div data-role="header" style="overflow:hidden;">
</div>
<div id = "home" data-role="content">
<input type ='button' id = "some_btn" value="press me">
</div>
</div>
<script type="text/javascript" src="/static/js/controllers.js"></script>
</body>
</html>
and within the javascript file
controllers.js
$('#some_btn').click(function()
{
alert('button pressed');
});
Any ideas on what I may be doing wrong here?
Since the content in the #page is loaded dynamically via ajax, click will not work, since it only works on elements that are on the page when the script is called.
You need to use the .on() method:
$('body').on('click','#some_btn',function()
{
alert('button pressed');
});
This seems like it would have a really obvious answer, however I cannot get a simple checkbox to uncheck with JQuery once I add Jquery Mobile.
Here is some very simple code as an illustration:
<html>
<head>
<title>Untitled</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
<script>
jQuery(function () {
jQuery('#a').change(function () {
if (jQuery(this).is(':checked')) {
jQuery('#b').removeAttr('checked');
}
});
jQuery('#b').change(function () {
if (jQuery(this).is(':checked')) {
jQuery('#a').removeAttr('checked');
}
});
});
</script>
</head>
<body>
<input type="checkbox" id="a"><label for="a">AAAA</label>
<input type="checkbox" id="b"><label for="b">BBBB</label>
</body>
</html>
This is a simple bit of code. When Checkbox 'A' gets checked, it should uncheck checkbox 'B', and vise verse. However it doesn't, and no error is written to the console.
This is using the standard version of Jquery & Jquery Mobile, linked directly to their site
If I remove the Jquery Mobile elements, by removing the following lines, then it works fine
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
Can anyone please enlighten me as to where I am going wrong, since this seems so simple yet I'm at an absolute loss as to what is going on.
Many thanks
Because you need to use .prop and then re-apply styles using .checkboxradio('refresh').
Check
$('selector').prop('checked', true).checkboxradio('refresh');
Uncheck
$('selector').prop('checked', false).checkboxradio('refresh');
I decided to use jQuery UI for my autocomplete opposed to a plugin because I read that the plugins are deprecated. My overall goal is to have an autocomplete search bar that hits my database and returns users suggestions of city/state or zipcodes in a fashion similar to google. As of now I am not even sure that the .autocomplete function is being called. I scratched everything I had and decided to start with the basics. I downloaded the most recent version of jQuery UI from http://jqueryui.com/download and am trying to get the example that they use here http://jqueryui.com/demos/autocomplete/ to work. All the scripts that I have included seem to be connected at least linked through Dreamworks so I am fairly certain that the paths I have included are correct. The CSS and Javascripts that I have included are unaltered straight from the download. Below is my HTML code and my backend PHP code that is returning JSon formated data. Please help me. Maybe I need to include a function that deals with the JSon returned data but I am trying to follow the example although I see that they used a local array.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQueryUI Demo</title>
<link rel="stylesheet" href="css/ui-lightness/jquery-ui-1.8.17.custom.css" type="text/css" />
<script type="text/javascript" src ="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src ="js/jquery-ui-1.8.17.custom.min.js"></script>
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#tags").autocomplete({
source: "search_me.php"
});
});
</script>
</head>
<body>
<div class="demo">
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</div><!-- End demo -->
<div class="demo-description">
<p>The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are tags for programming languages, give "ja" (for Java or JavaScript) a try.</p>
<p>The datasource is a simple JavaScript array, provided to the widget using the source-option.</p>
</div><!-- End demo-description -->
</body>
</html>
Below the PHP part.
<?php
include 'fh.inc.db.php';
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
$location = htmlspecialchars(trim($_GET['term'])); //gets the location of the search
$return_arr = array();
if(is_numeric($location)) {
$query = "SELECT
zipcode_id
FROM
user_zipcode
WHERE
zipcode_id REGEXP '^$location'
ORDER BY zipcode_id DESC LIMIT 10";
$result = mysql_query($query, $db) or die(mysql_error($db));
while($row = mysql_fetch_assoc($result)) {
extract($row);
$row_array['zipcode_id'] = $zipcode_id;
array_push($return_arr, $row_array);
}
}
mysql_close($db);
echo json_encode($return_arr);
?>
Thanks for the ideas. Here is an update.
I checked the xhr using firebug and made sure that it is responding thanks for that tip. also the above php code I hadn't initialized $return_arr so i took care of that. Also thanks for the clarification of the js required or rather not required. Now when I type in a zipcode a little box about a centimeter shows up underneath it but I can't see if anything is in there, I would guess not. I went to my php page and set it up to manually set the variable to "9408" and loaded the php page directly through my browser to see what it returned. This is what it returned.
[{"zipcode_id":"94089"},{"zipcode_id":"94088"},{"zipcode_id":"94087"},{"zipcode_id":"94086"},{"zipcode_id":"94085"},{"zipcode_id":"94083"},{"zipcode_id":"94080"}]
I then went to a JSON code validator at this url http://jsonformatter.curiousconcept.com/ at it informed me that my code is in fact returning JSON formatted data. Anymore suggestions to help me troubleshoot the problem would be terrific.
Wow after more research I stumbled across the answer on someone another post.
jquery autocomplete not working with JSON data
Pretty much the JSON returned data must contain Label or Value or both. Switched the zipcode_id to value in my $row_array and... boom goes the dynamite!
Your scripts (js files) references are not correct, should only be:
<!-- the jquery library -->
<script type="text/javascript" src ="js/jquery-1.7.1.min.js"></script>
<!-- the full compressed and minified jquery UI library -->
<script type="text/javascript" src ="js/jquery-ui-1.8.17.custom.min.js"></script>
The files "jquery.ui.core.js", "jquery.ui.widget.js" and "jquery.ui.position.js" are the separated development files, the jquery ui library is splitted into modules.
The file "jquery-ui-1.8.17.custom.min.js" contains them all, compressed and minified !
Concerning the data source, as stated in the "Overview" section of the Autocomplete documentation: when using a an URL, it must return json data, either of the form of:
an simple array of strings: ['string1', 'string2', ...]
or an array of objects with label (and a value - optionnal) property [{ label: "My Value 1", Value: "AA" }, ...]
I'm really not familiar with PHP so just make sure your php script returns one of those :-)
I must be missing something very basic in the CSS. My jQuery anchor button is functional, but it's rendering as a simple underlined label, not asa rounded-corner UI button. I would be grateful if someone could point out the error in this simple example.
Thanks
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML LANG="en-US">
<HEAD>
<TITLE>button test</TITLE>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Expires" content="Sat, 22 May 2010 00:00:11 GMT">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<SCRIPT type="text/javascript">
$(document).ready(
function() {
$('a','.test').click(function(){showIntro();return false;});
});
function showIntro()
{
document.location.href="intro.htm";
}
</script>
<body>
<div class='test'>Button</div>
</body>
</html>
You need to actually make it a button using .button(), like this:
$(function() {
$(".test a").button();
});
You can see the jQuery UI demos here and a demo of your markup working here.
You need to add the proper class to the link, using jQuery or otherwise.
Try:
Button
You do not need to make it a button you just need
$(".test a").click(function(){showIntro();return false;});
What you are trying to do with your selector passing the second paramater is the Scope.
The second paramater is not mean to be a string (selector) it should be a jQuery Object.
So if you wanted to do it your way your would have to say
var test = $('.test');
$('a',test).click...
But the 1st method is prefered over doing it this way.
Sorry to be providing an answer, if not "the" answer, to my own question, but I have discovered a clue as to what's going on, if not the ultimate cause of the behavior. Below is code cut and pasted from the Button example on the jQuery website; take it to jsFiddle and run it: it works. But if you remove this line relating to the input-button:
$("button, input:submit, a", ".demo").button();
then the anchor-button fails to render properly. Why is the anchor-element's rendering dependent on the existence of the input-button?
<script type="text/javascript">
$(function() {
$("button, input:submit, a", ".demo").button();
$("a", ".demo").click(function() { return false; });
});
</script>
<style>
</style>
<div class="demo">
<button>A button element</button>
<input type="submit" value="A submit button">
An anchor
</div><!-- End demo -->