I have an autocomplete text input:
<script type="text/javascript">
$(function()
{
var availableTags = <?php
$id_list = array("Name 1", "Name 2", "Name 3");
echo json_encode($id_list); ?>;
$("#FacultyName").autocomplete(
{
source: availableTags,
autoFocus:true
});
</script>
<input type="text" id="FacultyName">
Output:
I want do some task when user select on the available tag.
Is there any function like onClick or onChange to do it?
Autcomplete has a select event for this
Try like this
$("#FacultyName").autocomplete({
source: availableTags,
autoFocus: true,
select: function(event, ui) {
alert("select");
}
})
jQuery has the .change() method. Here is the API documentation to help.
https://api.jquery.com/change/
Related
I have autocomplete jQuery script working for pulling suggestions from MySQL database when typing in form fields on the page (3 input fields).
That is working fine, but what I would like is to when I select suggested option in the first field - all 3 fields should be filled.
Fields that I have right now is first name, last name, and company. When I select the first name - last name and company should be automatically filled with data.
Here's php:
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function()
{
$( "#first_name" ).autocomplete({
source: 'autocomplete.php'
});
});
$(function()
{
$( "#last_name" ).autocomplete({
source: 'autocomplete.php'
});
});
$(function()
{
$( "#company" ).autocomplete({
source: 'autocomplete.php'
});
});
</script>
</head>
<body>
<div id="wrapper">
<div class="ui-widget">
<p>First name</p>
<input type="text" id="first_name">
</div>
<div class="ui-widget">
<p>Last name</p>
<input type="text" id="last_name">
</div>
<div class="ui-widget">
<p>Company</p>
<input type="text" id="company">
</div>
</div>
</body>
</html>
And here's the autocomplete.php file:
<?php
$host="localhost";
$username="user";
$password="password";
$databasename="dbname";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
$searchTerm = $_GET['term'];
$select =mysql_query("SELECT * FROM jemployee WHERE first_name LIKE '%".$searchTerm."%'");
while ($row=mysql_fetch_array($select))
{
$spojeno = $row['first_name'] . ' ' . $row['last_name'] . ' ' . $row['kompanija'];
$data[] = $spojeno;
}
//return json data
echo json_encode($data);
?>
So, when the suggested option from "first_name" is selected - "last_name" and "company" should be filled with corresponding data from a database. Any suggestions?
Use something Jquery likes:
$(document).on('keyup', '#firstname', funtion(){
$.ajax({
type:"POST",
url:"ajax.php",
data:$("#firstname").val();
},
success:function (res){
$("#lastname").val(res.lastname);
$("#company").val(res.company);
},
)};
});
And PHP ajax.php file:
<?php
\\Select lastname, company with $_POST['data']
echo json_endcode($result);
Should check and handle the ajax response. If you can you this solution, please make it better.
What I did is passing the ajax "item" result as the autocomplete "value" :
It looks like this :
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Id, //the data that will be shown in the list !
value: item //item holds "Id" and "Name" properties
};
}))
}
I then subscribe the autoComplete "select" event to prevent it's default behaviour.
I then fill the different fields I need to :
select: function(event, ui){
//Update Customer Name Field on Id selection
event.preventDefault()
$("#CustomerId").val(ui.item.value.Id);
$("#CustomerName").val(ui.item.value.Name);
},
here's the entire autocomplete call, in case it helps ;)
$("#CustomerId").autocomplete({
source: function (request, response) {
$.ajax({
url: "/.../../GetAvailablePartnerInformations",
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Id,
value: item
};
}))
}
})
},
change: function (event, ui) {
//Forces input to source values, otherwise, clears
//NOTE : user could still submit right after typing => check server side
if (!ui.item) {
//http://api.jqueryui.com/autocomplete/#event-change -
// The item selected from the menu, if any. Otherwise the property is null
//so clear the item for force selection
$(event.target).val("");
$(event.target).addClass("is-invalid");
}
else {
$(event.target).removeClass("is-invalid");
}
},
select: function(event, ui){
//Update Customer Name Field on Id selection
event.preventDefault()
//Note : the "value" object is created dynamically in the autocomplete' source Ajax' success function (see above)
debugger;
$("#CustomerId").val(ui.item.value.Id);
$("#CustomerName").val(ui.item.value.Name);
},
messages: {
noResults: "",
results: function (resultsCount) { }
},
autoFocus: true,
minLength: 0
})
code:
<script>
$(function() {
$( "#college_name" ).autocomplete({
source: 'search.php',
minLength:2,
select: function(event, ui) {
var x = ui.item.value;
$("#college_name").attr('value',x);
}
});
});
</script>
<script>
$(document).ready(function(){
$("#college_name").select(function(){
alert("hi");
});
});
</script>
html code:
<input type="text" id = "college_name" name = "college_name" value="" placeholder = "College Name" autocomplete="off">
<input type='text' name='college_id' id='college_id'>
In this code when I wrote any college name in college_name input field autocomplete search i.e. search.php are working all college are showing. But when I select any college from autocomplete it does not show any message like (hi) or any thing. So, how can I fix this problem.
Thank You
Add alert message in Select event of autocomplete.
<script>
$(function() {
$( "#college_name" ).autocomplete({
source: 'search.php',
minLength:2,
select: function(event, ui) {
var x = ui.item.value;
$("#college_name").attr('value',x);
alert("hi");
}
});
});
</script>
I have a mysql database where I would like to use the autocomplete one.
So far I am able to receive the results of the query.
For example this is the result: [{"LNAME":"Napoleon","id":"1"}]
But I want the id of the customer in this case to be filled in another input field of my form. (so in Napoleons case I want the "1" to be filled in to my clienteID field of the form)
At the moment the field does not get updated.
Here's the HTML part:
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
minLength: 3,
select: function(event, ui) {
$('#clienteId').val(ui.item.id);
},
});
});
</script>
<form name='form_update_details' id='form_update_details' method='post' action=''>
<input type='text' name='clienteName' id='tag'>
<input type='text' name='clienteId' id='clienteId'>
</form>
Then the php part:
<?php
include("include/db.php");
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
$sql="SELECT ID, CONTACTS_LNAME, CONTACTS_FNAME FROM CRM_CONTACTS WHERE CONTACTS_LNAME LIKE '%$my_data%' or CONTACTS_FNAME LIKE '%$my_data%' ORDER BY CONTACTS_LNAME";
$result = mysqli_query($coni,$sql) or die(mysqli_error());
if($result)
{
while($row=mysqli_fetch_array($result))
{
$data[] = array(
'LNAME' => $row['CONTACTS_LNAME'],
'id' => $row['ID']
);
}
echo json_encode($data);
flush();
}
?>
Try with a sample data:use label and value as keys instead of LNAME and id. Use event.preventDefault(); to set the label in #tag field otherwise by default it will set the value.
var data = [
{
value: "1",
label: "jQuery"
},
{
value: "2",
label: "jQuery UI"
},
{
value: "3",
label: "Sizzle JS"
}
];
$(document).ready(function(){
$("#tag").autocomplete( {
source: data,
minLength: 3,
select: function(event, ui) {
event.preventDefault();
$("#tag").val(ui.item.label);
$('#clienteId').val(ui.item.value);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<form name='form_update_details' id='form_update_details' method='post' action=''>
<input type='text' name='clienteName' id='tag'>
<input type='text' name='clienteId' id='clienteId'>
</form>
Try this:
$( function() {
var projects = [
{
value: "1",
label: "jQuery"
},
{
value: "2",
label: "jQuery UI"
},
{
value: "3",
label: "Sizzle JS"
}
];
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
};
});
Html:
<div id="project-label">Select a project (type "j" for a start):</div>
<input id="project">
<input type="text" id="project-id">
Demo Fiddle
I have an auto-complete textbox where user can insert an actor name and it works fine. There is a button "browse movies" which should populate a dynamic dropdown showing list of movies by the actor that user has inserted in the text-box. Also, there is another button "add to the list" that if user click on it, the selected options of this dropdown (movies) whould be added to another dropdown which shows all selected movies by user.
Problem
I could populate dropdown dynamically when user clicked the button, also I could move the selected options to the new dropdown (selecteditems), but the problem is that I want to show this dropdown in a new pop-up window (not in the same page where user insert in the text-box). I really don't know how to do it.. should I make the ajax call in target.html (the new pop up window)? I appreciate if someone can let me know how I can do this.
This is what I tried:
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
$("#tags").on('autocompletechange change', function (){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}).change();
}
});
$('#btnRight').on('click', function (e) {
var selectedOpts = $('#movieName option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#selectedItems').append($(selectedOpts).clone());
$(selectedOpts).remove();
$("#movieName").hide();
$("#tags").val("");
e.preventDefault();
});
function openWindow() {
window.open("target.html","_blank","height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
}
</script>
<html>
<body>
<input type="textbox" name= "tag" id="tags" style="display:none;" placeholder="Enter an actor/actress name here" />
<input type=button onclick="javascript:openWindow()" value="Browse movies by this actor">
<select id="movieName" name="movieName[]" multiple="multiple" width="200px" size="10px" style=display:none;>
<input type="button" value=">> Add to selected list >>" id="btnRight" style="display:none;" />
<select id="selectedItems" name="selectedItems[]" multiple="multiple" style="width:200px; size:10px;">
</select>
</select>
</body>
</html>
You could try something like this. Sorry for any mistakes or if it's rubbish
target.html
// this goes in target.html
$('#tags').autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui) {
$("#tags").on('autocompletechange change', function () {
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
// here's some magic. using window.opener allows you
// to access variables and functions defined in the parent window.
window.opener.getMovies(selectedVal);
}).change();
}
});
page.html
// this stays in your parent window
function getMovies(value) {
$.post("actions.php", { q: value}, function (response) {
console.log(response);
$("#movieName").html(response).show();
});
}
i make a jquery autocomplete and its data come from mysql database.now i m facing a small problem in this.
i want to show product name in autocomplete as u see in code below & its working good.but after clicking submit button i want to insert product ID instead of product NAME.Below is my code
<?php
require_once "include/config.php";
$sql_product = "select * from tbl_product";
$res_product = mysql_query($sql_product);
?>
<script>
$(function() {
var availableTags = [
<?php
while($rs_product = mysql_fetch_array($res_product))
{
$prod_name = $rs_product['prod_name'];
?>
"<?php echo $prod_name; ?>" <?php echo ", "; ?>
<?php
}
?>
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
<label for="tags">Tags: </label>
<input id="tags" />
You can pass in your values to availableTags source in format like:
[{label:"Prod Name 1", value:1}, {label:"Prod Name2", value:2}]
Create a hidden input element, like
<input type="hidden" name="hidAutoComplete" value="" />
And:
$( "#tags" ).autocomplete({
source: availableTags,
select: function(event, ui) {
var selectedObj = ui.item;
$(this).val(selectedObj.label);
$('input[name="hidAutoComplete"]').val(selectedObj.value);
return false;
}
});
Hope it helps
TRY ( I assume there is prod_id column in your table )
var availableTags = [
<?php
while($rs_product = mysql_fetch_array($res_product))
{
$prod_id[] = $rs_product['prod_id'];
}
echo json_encode($prod_id);
?>
];
update
use json_encode