jQuery Autocomplete ignore 0 - php

Users enter values like 01234 and 12345. I would like to ignore the 0 when a users enters.
<input name="location" class="input-lg" style="width:100%;" id="location" type="text" size="50" placeholder="<?php echo $this->lang->line('inputhint');?>" />
$(function() {
var availableLocations =
<?php
// print the json array containing all zips
echo $locations;
?>
$("#location").autocomplete({
source: availableLocations,
minLength: 3,
focus: function (event, ui){
$('#location').val(ui.item.value);
return false;
},
select: function (event, ui){
$('#location').val(ui.item.value); // display the selected text
$('#locationid').val(ui.item.key); // save selected id to hidden input
return false;
},
change: function (event, ui){
// write value to hidden field
$( "#locationid" ).val( ui.item? ui.item.key : 0 );
return false;
}
});
});
Is there any way to do that? I tried a lot of things, but I can not handle it. Any idea?

The following is untested, but it works something like this:
$("#location").autocomplete({
source: function(request, response) {
// manipulate your search term
var yourTerm = parseInt(request.term);
// run a filter function on your data...
var filteredArray = $.map(availableLocations, function(item) {
// or whatever your matching rule is....
if( item.startsWith(yourTerm)){
return item;
} else{
return null;
}
});
// return the filtered values
response(filteredArray);
}
});

Related

JSON string in autocomplete key and value pair

I have an JSON string like
{"Name1":"ID1","Name2":"ID2"} which I have retrieved using json_encode of PHP.
How can I have an input field with Name1,Name2 in autocomplete options and once Name1 is selected, ID1 to be taken in a hidden field?
I am using Jquery ui autocomplete.
var NameIDJsonString = <?php echo $NameIDJsonString; ?>;
$(function () {
$('#JSONName').autocomplete({
source: function (request, response) {
response($.map(NameIDJsonString, function (value, key) {
return {
label: key,
value: value
};
}));
},
select: function (event, ui) {
$("#JSONName").val(ui.item.text); // display the selected text
$("#JSONID").val(ui.item.value); // save selected id to hidden input
}
});
});
}
<html>
<body>
<input id="JSONName" name="JSONName" size="30" class="ui-autocomplete-input" autocomplete="on" type="text" >
<input id="JSONID" name="JSONID" size="30" class="ui-autocomplete-input" autocomplete="on" type="hidden" >
http://jsfiddle.net/mahesh1393/Aa5nK/4166/
var source = [ ];
var mapping = { };
for(var i = 0; i < NameIDJsonString.length; ++i) {
source.push(NameIDJsonString[i].Name);
mapping[NameIDJsonString[i].Name] = NameIDJsonString[i].ID;
}
$('#JSONName').autocomplete({
minLength: 1,
source: source,
select: function(event, ui) {
"use strict";
var summary=ui.item.value;
$("#JSONID").val(mapping[name]);
},
change: function( event, ui ) {
val = $(this).val();
exists = $.inArray(val,source);
if (exists<0) {
$(this).val("");
alert("Please enter a value from the list");
return false;
}
}
});
I have modified my JSON string as each object like
{Name:"Name1",ID:"ID1"}
{Name:"Name2",ID:"ID2"}
and hence the above code shall help. Thanks.:)

Jquery autocomplete displaying more detail in drop down

I have a autocomplete function that works fine but where I want to extend the drop down details a bit. It looks like this:
Datafile (form-lookup.php):
if ($db)
{
$fetch = mysqli_query($db,"SELECT * FROM uni_labels where label_name like '%" . $_GET['term'] . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['label'] = htmlspecialchars_decode($row['label_name']);
$row_array['lookupid'] = $row['id'];
$row_array['address'] = $row['label_address'];
$row_array['number'] = $row['label_number'];
$row_array['postalcode'] = $row['label_postalCode'];
$row_array['country'] = $row['label_country'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysqli_close($db);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
My page that retreives the data looks like this:
$(function() {
$("#step1Name").autocomplete({
source: "/pages/form-lookup.php?country=dk",
minLength: 2,
select: function(event, ui)
{
$('#step1Name').val(ui.item.address);
$('#lookupid').val(ui.item.lookupid);
$('#vej').val(ui.item.address);
}
});
});
<input maxlength="100" type="text" required="required" class="form-control input-lg" name="step1Name" id="step1Name" />
Everyting works just great, but I would like for my drop down to show both $row_array['label'] and $row_array['address'], and when I select a value in the drop down, the input box will only output the $row_array['label'] value.
In the datafile I have tried to add the address to the label, like this:
$row_array['label'] = htmlspecialchars_decode($row['label_name'])." - ".$row['label_address'];
This displays the value fine in the drop down, but when selecting the choice, the input box of course contains too much data, where I only want it to display the label_name.
Can someone point me in the right direction?
Thanks in advance.
Add this to your autocomplete code:
select: function(event, ui) {
event.preventDefault();
var name = ui.item.value.split('-')[0];
$("#starter").val(name);
},
focus: function(event, ui) {
return false;
}
So your updated autocomplete code will be like that:
$("#step1Name").autocomplete({
source: "/pages/form-lookup.php?country=dk",
minLength: 2,
select: function(event, ui) {
event.preventDefault();
var name = ui.item.value.split('-')[0];
$("#starter").val(name);
return false;
},
focus: function(event, ui) {
return false;
}
});

jquery Auto complete response coming as array how can i call two fields like name and photo

This is the form field with input type text.
<span>
<img src="images/author2.jpg" width="50" /> //in Database i have profilepic/userimage.jpg and the image shown in above is a static image.
<input class="searchStudent" type="text" autocomplete="off">
</span>
I have entered letter "A" and the response is coming as a array.i want to show the photo and names of the user how can i do that...?
This is my from script to get the details:
/*Search Student starts here*/
$(document).on("focus keyup", "input.searchStudent", function (event) {
$(this).autocomplete({
source: 'gdcontroller.php?action=search',
select: function (event, ui) {
event.preventDefault();
this.value = ui.item.label;
},
focus: function (event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
});
/*Search Student ends here*/
This is my controller, here I am searching available students with name "A"
and fetching their details:
if($_GET['action']=="search" && $_GET['term']!='')
{
$keysearch = $_GET['term'];
$studentValue = trim($_GET['studentname']);
$studentsQuery =$conn->query('select s.student_pid,i.email,s.student_email,s.student_fname,s.student_lname,s.profile_pic from r_job_invitations i
LEFT JOIN tbl_students s ON i.email = s.student_email where i.id_job =54 and accounttype = 1 and inv_res = 1 and student_fname LIKE "'.$keysearch.'%" OR student_lname LIKE "'.$keysearch.'%" ')or die(mysqli_error());
$studentData = array();
while($student = $studentsQuery->fetch_assoc()){
$studentData[]= $student;
}
echo json_encode($studentData);
exit;
}
<div id="photoContainer"></div>
$(document).on("focus keyup", "input.searchStudent", function(event) {
$(this).autocomplete({
source: 'gdcontroller.php?action=search',
select: function (event, ui) {
event.preventDefault();
//I'm having trouble here; even name is not coming:
student.student_fname.value = ui.item.student.student_fname;
$("#photoContainer").append('<img src="' + ui.item.student.profile_pic + '">');
},
focus: function(event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
});

Grab Value of Second Term using jQuery UI Autocomplete

Thanks for the response, #ManselUK
Fixed this part with finding values(below)
But, when I SELECT a value, it doesnt set the value of the hidden element, why not?
I'm getting error: Uncaught TypeError: Cannot set property 'value' of null when I select a value from autocomplete..
Php code which is called upon entering 5 characters:
try{
$occupation = mysql_real_escape_string($_GET['term2']); //////
echo 'term 2 '. $occupation;
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth = $dbh->prepare(
'SELECT occupID, occupVal From Occupation WHERE occupVal = ?');
$sth->bindParam(1, $occupation);
$sth->execute();
$jsonArray = array();
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) {
$jsonArray[] = array(
'label' => $result['occupVal'],
'value' => $result['occupVal']."|".$result['occupID']);
}
print json_encode($jsonArray); // json encode that array
} // try
the catch{} block of code, will send errors to a file, but that file has no errors in it.
The HTML Form Input:
<label for="occup">What is your occupation? <br /></label>
<div class="ui-widget">
<input id="occup" type="text" name="term2" value="e.g. Carpenter, Developer, etc" onFocus="clearText(this)" /><br />
<input type="hidden" id="actualOccup" name="actualOccupval" value="" />
The JS that is called upon entering something:
<script type="text/javascript">
$(document).ready(function()
{
// Zipcode Field
$('input#zip').autocomplete({
dataType: "json",
source: "../src/php/registration/getFanLoc.php",
minLength: 4,
select: function(event, args){
event.preventDefault();
var joinedValues = args.item.value;
var id = joinedValues.split("|")[0];
var cityAndState= joinedValues.split("|")[1];
document.getElementById('actualZip').value = cityAndState ;
document.getElementById('zip').value = id;
}
});
// Occupation Field
$('input#occup').autocomplete({
source: function(request, response) {
$.getJSON("../src/php/registration/getFanOccupation.php", { term2: request.term }, response);
},
minLength: 5,
select: function(event, args){
event.preventDefault();
var joinedValues = args.item.value;
var id = joinedValues.split("|")[0];
var occupValAndId= joinedValues.split("|")[1];
$('#actualOccupval').val(occupValAndId);
$('#occup').val(id);
}
});
});
</script>
I've tried debugging:
- Check error log for this file. (no errors)
- Check the SELECT query , the value for occupVal in database is a VARCHAR, in SQL the value is found by doing occupVal = 'some val here'; does jQuery need these quotes?
- if I access getFanOccupation.php?term2=Computer Programmer directly it outputs: term 2 Computer Programmer[{"label":"Computer Programmer","value":"Computer Programmer|183"}]
- Which is RIGHT, the problem is if I get Computer Programmer value and paste directly in input, or even start to write it, it
Fixed JS: - this code works, was select wrong ID for occupation, that's why it wasn't showing the hidden forms field value
$(document).ready(function()
{
// Zipcode Field
$('input#zip').autocomplete({
dataType: "json",
source: "file1.php",
minLength: 4,
select: function(event, args){
event.preventDefault();
var joinedValues = args.item.value;
var id = joinedValues.split("|")[0];
var cityAndState= joinedValues.split("|")[1];
document.getElementById('actualZip').value = cityAndState ;
document.getElementById('zip').value = id;
}
});
// Occupation Field
$('input#occup').autocomplete({
source: function(request, response) {
$.getJSON("file.php", { term2: request.term }, response);
},
minLength: 5,
select: function(event, args){
event.preventDefault();
var joinedValues = args.item.value;
var id = joinedValues.split("|")[0];
var occupValAndId= joinedValues.split("|")[1];
$('#actualOccup').val(occupValAndId);
$('#occup').val(id);
}
});
});
Use this :
source: function(request, response) {
$.getJSON("../src/php/registration/getFanOccupation.php", { term2: request.term }, response);
}
on the second autocomplete. Docs for $.getJSON() here
From the docs :
A request object, with a single property called "term", which refers
to the value currently in the text input. For example, when the user
entered "new yo" in a city field, the Autocomplete term will equal
"new yo".
Full code :
$('input#occup').autocomplete({
source: function(request, response) {
$.getJSON("../src/php/registration/getFanOccupation.php", { term2: request.term }, response);
},
minLength: 4,
select: function(event, args){
event.preventDefault();
var joinedValues = args.item.value;
var id = joinedValues.split("|")[0];
var occupValAndId= joinedValues.split("|")[1];
$('#actualOccupval').val(occupValAndId);
$('#occup').val(id);
}
});
Note also changed document.getElementById('blah').value = to $('#blah').val() as your already using jQuery ... docs for the val() method here

Why is jQuery autocomplete updating all elements on my cloned form?

I have a form that uses the jQuery UI autocomplete function on two elements, and also has the ability to clone itself using the SheepIt! plugin.
Both elements are text inputs. Once a a value is selected from the first autocomplete (continents), the values of the second autocomplete (countries) are populated with options dependent on the first selection.
My problem is, when clones are made, if the user selects an option from the first autocomplete (continent), it changes the first input values on all clones. This is not happening for the second input (country).
What am I missing?
Note: the #index# in the form id and name is not CFML. I am using PHP, and the hash tags are part of the SheepIt! clone plugin.
Javascript:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script src="../../scripts/jquery.sheepIt.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
$('#location_container_add').live('click', function() {
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
var location_container = $('#location_container').sheepIt({
separator: '',
allowRemoveLast: true,
allowRemoveCurrent: false,
allowRemoveAll: false,
allowAdd: true,
allowAddN: false,
maxFormsCount: 10,
minFormsCount: 1,
iniFormsCount: 1
});
var continent_autocomplete = {
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
}
var continent_autocomplete_keyup = function (event){
var code = (event.keyCode ? event.keyCode : event.which);
event.target.value = event.target.value.titleCase();
}
var country_autocomplete = {
source: loadcountry,
}
var country_autocomplete_keyup = function (event){
event.target.value = event.target.value.titleCase();
}
var country_autocomplete_focus = function(){
if ($(this).val().length == 0) {
$(this).autocomplete("search", " ");
}
}
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
</script>
HTML:
<div id="location_container">
<div id="location_container_template" class="location_container">
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name_#index#" name="continent_name_#index#" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete_#index#" name="country_autocomplete_#index#" class="country_autocomplete" />
</div>
</div>
</div>
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
That code says explicitly to set the value of every <input> with class "continent_autocomplete" to the selected value.
You probably want something like
$(this).val(ui.item.value);
but it depends on how your autocomplete code works.
This line: $("input.continent_autocomplete").val(ui.item.value); is updating all inputs with class continent_autocomplete.
UPDATE:
From jQueryUI Autocomplete Doc:select:
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing.
You shouldn't need the select bit at all, it looks like you're simply trying to achieve the default action.

Categories