I have a textbox (auto-complete) where users can enter an actor/actress name which works fine.
As soon as user insert a name in the textbox, a dynamic dropdown should be populated showing list of movies by that actor.
Problem:
when user insert a name in the textbox, an empty dropdown is populated, but if user click on the dropdown or somewhere in the page, then list of movies are shown in the dropdown! Another issue is that if user press Enter inside the textbox (after he inserted the name), the textbox will be cleared!!
Could someone kindly let me know what is the problem with my code?
Here is the code:
<html>
<head>
<link type="text/css" href="res/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="res/jquery.min.js"></script>
<script type="text/javascript" src="res/jquery-ui.min.js"></script>
<script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js"type="text/javascript"type="text/javascript"></script>
</head>
<body>
<form>
<p>
<input type="textbox" name= "tag" id="tags" placeholder="Enter an actor/actress name here" />
</p>
<p>
<select id="movieName" name="movieName[]" multiple="multiple" width="200px" size="10px" style="display:none;">
</select>
</p>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
focus: function( event, ui ){
event.preventDefault();
return false;
},
select: function (event, ui){
$("#tags").on('autocompletechange change', function () {
var selectedVal = $(this).val();
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}).change();
}
});
});
</script>
</form>
</body>
</html>
and this is actions.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$html = "";
if(isset($_POST['q']) && !empty($_POST['q'])){
try{
include('imdbConnection.php');
$sql = $conn->prepare("SELECT DISTINCT movieName FROM cast_movie WHERE castName = :q");
$sql->execute(array(':q' => $_POST['q']));
while($rows = $sql->fetch(PDO::FETCH_ASSOC)){
$option = '<option value="' . $rows['movieName'] . '">' . $rows['movieName'] . '</option>';
$html .= $option;
}
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
echo $html;
exit;
}
?>
this part.
$("#tags").on('autocompletechange change', function () {
var selectedVal = $(this).val();
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}).change();
Action will be made on "change". . try to change it as on "keyup"
change will only be trigger if the element loses its focus.
EDIT: you should change this part ..
$("#tags").on('autocompletechange keyup', function () {
var selectedVal = $(this).val();
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}).keyup();
Related
I've used jquery to get an "id" as a value for an input according to a dropdown value. Now the problem is, I want to use the 'id' to insert value to some other inputs. I don't know which event method to be used. For testing, I used the keyup method to check if the code works, when I manually type in a number, it works. So the problem is with the event method I choose. Please give me some suggestions.
//Get id
$(document).ready(function() {
$('#salary_eid').change(function() {
var sid = $(this).val();
var data_String = 'sid=' + sid;
$.get('search1.php', data_String, function(result) {
$.each(result, function(){
$('#can').val(this.c_id);
});
});
});
//display other information
$('#can').change(function() {
var id = $(this).val();
var data_String1 = 'id=' + id;
$.get('search.php', data_String1, function(result1) {
$.each(result1, function(){
$('#morning_rate').val(this.cMorning);
$('#night_rate').val(this.cNight);
$('#ot_rate').val(this.clientOt);
});
});
});
});
<label>Name</label>
<input type="text" name="salary_eid" />
<select id="salary_eid">
<option>opt1</option>
<option>opt2</option>
</select>
<input type="hidden" name="can" id="can" class="form-control" >
You can trigger the keyup() event from the id code, this will then work through a manual or jQuery edit,
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
//Get id
$(document).ready(function() {
$('#salary_eid').change(function() {
var sid = $(this).val();
$('#can').val(sid).keyup();
});
});
//display other information
$(document).on('keyup', '#can', function() {
console.log($(this).val())
});
</script>
<label>Name</label>
<input type="text" name="salary_eid" />
<select id="salary_eid">
<option>opt1</option>
<option>opt2</option>
</select>
<input type="text" name="can" id="can" class="form-control" />
If you are going to hide the second input then I might suggest using a function instead without an input,
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
//Get id
$(document).ready(function() {
$('#salary_eid').change(function() {
var sid = $(this).val();
display_info(sid)
});
});
//display other information
function display_info(value) {
console.log(value)
};
</script>
<label>Name</label>
<input type="text" name="salary_eid" />
<select id="salary_eid">
<option>opt1</option>
<option>opt2</option>
</select>
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 want to show data from database on key change, they will input place name, and it will check database with getPlaces.php and output on showlist div.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$('form')[0].reset();
$("form").attr("autocomplete", "off");
//$("#place").focus();
$('#place').on('keyup', function(e){
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#place').val();
if (keyword.lengtd>= min_length) {
$.post("getPlaces.php", $('form').serialize(), function(response) {
$('#showlist').html(response);
$('#showlist').show();
});
}
});
});//]]>
</script>
</head>
<body id="up">
<div id="form"><form><input type="text" id="place" name="place" placeholder="write area name .." /></form></div>
<div id="showlist">
</div>
</body>
</html>
php file is working perfectly. but i am not getting any content!
You misspelled keyword.lengtd. It should be keyword.length.
use this script code
<script type='text/javascript'>
$(window).load(function(){
$('form')[0].reset();
$("form").attr("autocomplete", "off");
//$("#place").focus();
$('#place').on('keyup', function(e){
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#place').val();
if (keyword.length >= min_length) {
$.post("getPlaces.php", $('form').serialize(), function(response) {
$('#showlist').html(response);
$('#showlist').show();
});
}
});
});
</script>
Im having a problem when im trying to auto populate more than one text field as well as dropdown list ... This UI fetches data from DB for auto populating ... actually the problem arises when i click the + button for additional textfield and dropdown list ... for the first text field and drop down list im getting auto populated correctly but i face problem when i try for the second row ... please correct my errors
`
</title>
<link rel="stylesheet" type="text/css" href="jquery-ui.css"/>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="jquery-1.11.0.min.js"></script>
<script src="jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#add1').click(function() {
$("#box").append(
$('<div><input type="text" name="property_id" id="property_id"/>\n\
<select disabled="" name="unit_id" id="unit_id">\n\
<option></option>\n\
</select><img src="remove.png" width="20" height="20" border="0" align="top" class="add1" id="remove" /><br></div>')
);
});
$('body').on('click', '#remove', function() {
$(this).parent('div').remove();
});
});
</script>
<script type="text/javascript">
jQuery(document).ready(function() {
$('#property_id').autocomplete({
source: 'unit.php',
minLength: 1,
select: function(evt, ui)
{
$.ajax({
url: "property.php",
data: {propertyid: ui.item.property_id},
dataType: 'json',
type: 'POST',
success: function(data) {
var pname = ui.item.value;
console.log("combo data === ", pname, data);
$('select[name="unit_id"]').empty();
$('select[name="unit_id"]').append($('<option>').text("Select"));
for (var i = 0; i < data.length; i++) {
$('select[name="unit_id"]').append(
$('<option>', {value: data[i]["unit_id"]}).text(data[i]["unit_id"])
);
}
$('select[name="unit_id"]').removeAttr('disabled');
}
});
}
});
});
</script>
</head>
<body>
<div id="box">
<input type="text" name="property_id" id="property_id"/>
<select disabled="" name="unit_id" id="unit_id">
<option></option>
</select>
<img src="add.png" width="20" height="20" border="0" align="top" class="add" id="add1" /><br>
</div>
</body>
`
It is because you bind autocomplete on load. So the new item you created will not be bound with ui code.
You should bind the new item you created with the autocomplete. Like you did on load.
You can make binding a function and call it on load and after you created the item. Like,
var bindAutoComplete = function(elem) {
$(elem).autocomplete({
source: 'unit.php',
minLength: 1,
select: function(evt, ui)
{
$.ajax({
url: "property.php",
data: {propertyid: ui.item.property_id},
dataType: 'json',
type: 'POST',
success: function(data) {
var pname = ui.item.value;
console.log("combo data === ", pname, data);
$('select[name="unit_id"]').empty();
$('select[name="unit_id"]').append($('<option>').text("Select"));
for (var i = 0; i < data.length; i++) {
$('select[name="unit_id"]').append(
$('<option>', {value: data[i]["unit_id"]}).text(data[i]["unit_id"])
);
}
$('select[name="unit_id"]').removeAttr('disabled');
}
});
}
});
}
then in your on load
jQuery(document).ready(function() {
bindAutoComplete($('#property_id')[0]);
});
and in your add item method
$('#add1').click(function() {
var newItem = $('<div><input type="text" name="property_id" id="property_id"/>\n\
<select disabled="" name="unit_id" id="unit_id">\n\
<option></option>\n\
</select><img src="remove.png" width="20" height="20" border="0" align="top" class="add1" id="remove" /><br></div>');
bindAutoComplete(newItem.find("#property_id")[0]);
$("#box").append(newItem);
});
Warning, this code seems messy but to make you get the idea of binding this should work.
When you click add you are creating elements that have the same id as existing ones so this will fail. Give your created element a unique id.
You'll also need unique names if you are submitting, or add them as an array
I've also changed your remove id and changed the class:
<script type="text/javascript">
$(document).ready(function() {
var i = 0;
$('#add1').click(function() {
$("#box").append(
$('<div><input type="text" class="property_input" name="property_id[]" id="property_id' + i + '"/>\n\
<select disabled="" class="unit_select" name="unit_id[]" id="unit_id' + i + '">\n\
<option></option>\n\
</select><img src="remove.png" width="20" height="20" border="0" align="top" class="remove" /><br></div>')
);
i++;
});
$('body').on('click', '.remove', function() {
$(this).parent('div').remove();
i--;
});
});
</script>
I'm not sure exactly how autocomplete works but I reckon you'll have to give your select and inputs a class (as i have done) and loop through them, grab the id and call your ajax
How can I set the returned value to be added as a value of a textbox instead of a div ?
for example <input type="text" id="link" name="link" value="HERE" />
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js'></script>
<script language='JavaScript'>
setInterval( 'SANAjax();', 1000 );
$(function() {
SANAjax = function(){
$('#dataDisplay').load('yourfile.php');
}
});
</script>
<div id="dataDisplay"></div>
$.get("yourfile.php", function(data){
$("#link").val(data);
});
EDIT:
var SANAjax = function(){
$.get("yourfile.php", function(data){
$("#link").val(data);
setTimeout(SANAjax, 1000);
}).fail(function(){
setTimeout(SANAjax, 1000);
});
};
$(function(){
SANAjax();
});