Grab Value of Second Term using jQuery UI Autocomplete - php

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

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 ignore 0

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);
}
});

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;
}
});
});

Display information based on the autocomplete selected value

I have dynamic text field at Demo JSFiddle and I have done the autocomplete part for my item part no.
$ (document).ready(function() {
$("#addField").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div id=\"field" + intId + "\"/>");
var fpartNo = $("<input type=\"text\" name=\"erfq_partNo[]\" class=\"partNumber\"/>");
var fDescription = $("<input type=\"text\" name=\"erfq_desc[]\" disabled/>");
var fPrice = $("<input type=\"text\" name=\"erfq_price[]\" disabled style=\"width:80px\"/>");
// remove textboxes and dropdown boxes
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fpartNo);
fieldWrapper.append(fDescription);
fieldWrapper.append(fPrice);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
$(".partNumber").autocomplete({
minLength:1,
source: 'readPart.php',
select: function(event, ui){
var selected = ui.item.value;
}
});
});
});
readPart.php
$searchTerm = $_GET['term'];
$getPartSQL = base_executeSQL("SELECT * FROM eitem_item where eitem_item_part_no LIKE '%".$searchTerm."%' ORDER BY eitem_item_part_no" );
while($Partdata_row = base_fetch_array($getPartSQL))
if (base_num_rows($getPartSQL)!= 0)
{
$data[] = $Partdata_row['eitem_item_part_no'];
}
echo json_encode($data);
The first text field is uses for entering the part No.
My question is once the part no has been entered, the other relevant information (description and price) will be displayed at the other readonly text fields which the data are extract from my database. I have no idea what to continue with this select: function(event, ui){. Any help will be appreciated.
well, if you want to get the data on the basis of part # from database you can trigger an ajax call on blur of text box part number.
you can do something like this
$("#partNum").blur(function(){
var part = $("#partNum").val();
$.ajax({
type: 'get',
url:'/echo/js/?js='+part, //url to your database fetcher code.
complete: function (response) { //response contains what you got from pap page
$('textarea#des').val(response.responseText); //set textarea and textbox value popping out from db file
}
});
});
Here is HTML snippet to this request.
<input type = 'text' id = 'partNum' name = 'parts' />
<textarea id = "des" name = 'description' disabled></textarea>
FIDDLE
this will work on blur means when clicked outside the textbox. But if you want to get real time data(while user is typing) then you've to bombard the ajax requests on keyup event.
something like this:
$("#partNum").keyup(function(){
var part = $("#partNum").val();
$.ajax({
type: 'get',
url:'/echo/js/?js='+part,
complete: function (response) {
$('textarea#des').val(response.responseText);
}
});
});
FIDDLE here
Hope this will help.

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