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
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
})
I have this jquery script (slider):
<script>
$( function() {
$( "#slider-range-max" ).slider({
range: "max",
min: 1,
max: 25,
value: 1,
slide: function(event, ui) {
$("#amount").val(ui.value);
}
});
$( "#amount" ).val( $("#slider-range-max").slider("value") );
});
</script>
This is my html outout:
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="slider-range-max"></div>
I want the value of my slider stored as a php variable.
To call upon a php code that might have some logic in it, you need to have your html and javascript in a file, then your php code in a different file, like so :
html_file.php (contains only html template and javascript).
html part:
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="slider-range-max"></div>
Javascript part:
<script>
$( function() {
$( "#slider-range-max" ).slider({
range: "max",
min: 1,
max: 25,
value: 1,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
},
change: function(event, ui) {
$.post('php_file.php', {slider_val: ui.value}).done(
function(result) {
//your php code sends result back here.
//do something with result.
console.log(result);
}
);
}
});
$( "#amount" ).val( $( "#slider-range-max" ).slider( "value" ) );
});
</script>
php_file.php (contains the php code and logic).
you then retrieve the value in your php code like so:
<?php
//$slider_val contains the value of your slider
$slider_val = $_POST['slider_val'];
//you can output the value back to your javascript like so
echo $slider_val;
You can send the input value to php like this
HTML
<input type="text" placeholder="Amount" onkeyup="send(this.value)">
SCRIPT
<script>
function send(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("value").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "send.php?value=" + str, true);
xmlhttp.send();
}
</script>
PHP
$value = $_REQUEST["value"];
echo $value;
Try this. Hope it helps to solve your problem.
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'm trying to insert a row into my repair_history table from a form inside a dialog box using ajax.
Here is the function that opens the dialog box with the form:
<script>
$(function() {
$( "#repair-dialog" ).dialog({
autoOpen: false,
height: 300,
width: 450,
modal: true,
buttons: {
"Save": function() {
insert(
$( "#repair-dialog-date" ).val(),
$( "#repair-dialog-id" ).val(),
$( "#repair-dialog-comment" ).val(),
$( "#repair-dialog-save_type" ).val()
);
$( this ).dialog( "close" );
setTimeout(function(){location.reload(true);},500);
},
"Cancel": function() {
$( this ).dialog( "close" );
}
},
close: function() {
}
});
$( "#record_repair" ).click(function() { $( "#repair-dialog" ).dialog( "open" ); });
});
function insert(date,id,comment,save_type) {
mydata = {
"date" : date ,
"id" : id ,
"comment" : comment ,
"camera_id" : "<?php= $products['camera_id']?>" };
$.ajax({
type: "POST",
url: "localhost/cibs/index.php/api/record_save/"+save_type,
data: {data:JSON.stringify(mydata)},
dataType: "json",
cache : false
});
}
and here is the function inside the api.php controller that tries to insert:
function record_save()
{
$this->load->database();
$mydata = $this->input->post('data');
$date = $mydata['date'];
$comment = $mydata['comment'];
$id = $mydata['id'];
$camera_id = $mydata['camera_id'];
$table = "repair_history";
$data = array("camera_id" => $camera_id, "repair_id" => $id, "date" => $date, "comment" => $comment);
$this->db->insert($table,$data);
}
and heres the dialog box:
<div id="repair-dialog" title="Add New Repair" style="font-size: 15px;">
<form id="repair">
<input style="height:0px; top:-1000px; position:absolute" type="text" value="">
Repair id: <input type="text" id="repair-dialog-id" /><br>
Repair date: <input type="text" id="repair-dialog-date" /><br>
Comment: <input type="text" id="repair-dialog-comment" /><br>
<input type="hidden" value="repair" id="repair-dialog-save_type">
</form>
</div>
Any replies really appreciated! Thanks! :)
You don't need stringify your object:
$.ajax({
type: "POST",
url: "http://localhost/cibs/index.php/api/record_save/"+save_type,
data: mydata,
dataType: "json",
cache : false
});
And in php:
function record_save()
{
$this->load->database();
$table = "repair_history";
$data = array(
"camera_id" => $this->input->post('camera_id'),
"repair_id" => $this->input->post('id'),
"date" => $this->input->post('date'),
"comment" => $this->input->post('comment')
);
$this->db->insert($table,$data);
}
I'm not sure how your function $this->input->post('data') works, but you are posting the data as a json string, so you should make sure that you json_decode that data first.
Replace
$mydata = $this->input->post('data');
By
$mydata = json_decode($this->input->post('data'), true);
i'm trying to use jquery autocomplete with dynamic textfield generated, autocomplete works but the main problem is i cant populate textfield with name 'alamat' properly. How to set current textfield 'alamat' value properly in autocomplete ?
HTML
<form id="myForm" name="myForm" method="post">
<table id="myTable" border="1" cellpadding="1" cellspacing="1">
<thead>
<th>No</th><th>Nama</th><th>Alamat</th>
</thead>
<tbody></tbody>
</table>
<input id="addButton" name="addButton" type="button" value="Add an input" />
<input id="removeButton" name="removeButton" type="button" value="Remove an input" />
</form>
JS
<script type="text/javascript">
var counter = 1;
$(function() {
var options = {
source: 'autocomplete.php',
minLength: 2,
focus: function( event, ui ) {
$( '#nama_' + counter ).val( ui.item.value );
$( '#alamat_' + counter ).val( ui.item.alamat );
console.log(ui.item.alamat);
},
select: function( event, ui ) {
$( '#nama_' + counter ).val( ui.item.value );
$( '#alamat_' + counter ).val( ui.item.alamat );
console.log(ui.item.alamat);
}
};
$('input.searchNama').live("keydown.autocomplete", function() {
$(this).autocomplete(options);
});
var addInput = function() {
if (counter > 1){
$('input#removeButton').removeAttr('disabled');
}
var inputHTML = ' <tr><td><div id="' + counter + '">'+ counter +'</div></td><td><input type="text" id="nama_' +counter + '" class="searchNama" name="nama_' + counter +' " value="" /></td><td><input type="text" id="alamat_' + counter + '" class="searchAlamat" name="alamat_' + counter + '" value="" /></td></tr>';
$(inputHTML).appendTo("table#myTable tbody");
$("input.searchNama:last").focus();
counter++;
};
var removeInput = function() {
counter--;
if(counter == 1){
$('input#removeButton').attr('disabled','disabled');
counter++;
console.log('Jika Counter == 1 :' + counter);
} else {
$("table#myTable tbody tr:last").remove();
console.log('Jika Counter != 1 :' + counter);
}
};
if (!$("table#myTable tbody").find("input.searchNama").length) {
addInput();
}
$("input#addButton").click(addInput);
$("input#removeButton").click(removeInput);
});
</script>
my autocomplete.php generate JSON result
[{
"label": "Aditya Nursyahbani - Jl. Bratasena IX Blok U6 No. 7",
"value": "Aditya Nursyahbani",
"alamat": "Jl. Bratasena IX Blok U6 No. 7"
},
{
"label": "Slamet Aji Pamungkas - Jl. Melati 2 No. 3",
"value": "Slamet Aji Pamungkas",
"alamat": "Jl. Melati 2 No. 3"
}]
I upload my script on fiddle in this link!
thanks in advanced.
$('input.searchAlamat').val(ui.item.alamat);
Your selector will populate all inputs with class='searchAlamat' that are contained in the page.
WIthin the select callback, this will be the current input instance that autocomplete is bound to so you can traverse within the row it is in:
$(this).closest('tr').find('input.searchAlamat').val(ui.item.alamat);
DEMO
Note that I removed focus functionality