How to automatically add instead of showing with javascript ajax - javascript

How can I change this script which right now showing me the code or the name when is equal to the code or name I suggest in the input?
I need that instead of showing me the name the javascript added it automatically
Here are two images:
Here the code :
//autocomplete script
$(document).on('focus','.autocomplete_txt',function(){
type = $(this).data('type');
if(type =='cod' )autoTypeNo=0;
if(type =='nombreProd' )autoTypeNo=1;
$(this).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'include/ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
beforeSend: function(){
$('#msgCod').html('<img src="images/ajax-loader.gif"/> verificando');
},
success: function( data ) {
if(data == '') {
$('#submit').attr("disabled", true);
$('#msgCod').html("<div class='alert alert-danger alert-dismissible' role='alert'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>×</span></button>Este producto no existe en la base</div>");
} else if(data != '') {
$('#submit').attr("disabled", false);
$('#msgCod').html("");
}
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[autoTypeNo],
value: code[autoTypeNo],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#cod_'+id[1]).val(names[0]);
$('#nombreProd_'+id[1]).val(names[1]);
$('#proveedor_'+id[1]).val(names[2]);
$('#maskedDate_'+id[1]).val(names[3]);
$('#venta_'+id[1]).val(names[4]);
$('#existencia_'+id[1]).val(names[5]);
calculateTotal();
}
});
});

Related

jQuery autocomplete function brings the item from the database based on my typing word but result shows as just horizontal line of list

The jQuery autocomplete function brings the item from the database based on my typing word but result shows as just horizontal line of list. Attached image is showing how the result looks like.
HTML:
<form class="navbar-seach pull-center">
<div>
<input type="text" placeholder="Search Productstyle="width:550px; height:40px;padding-left: 10px;margin-top: 20px;" id="searchBox" onkeyup="if (event.keyCode === 13) {searchResults(this.value); this.value = '';}">
</div>
</form>
PHP:
include 'searchbox.php';
$switch_id = filter_input(INPUT_POST, 'switch_id', FILTER_SANITIZE_SPECIAL_CHARS);
if (isset($_POST['name_startsWith']))
$searchWordResults = $_POST['name_startsWith'];
else
$searchWordResults = null;
switch($switch_id){
case 1:
$userObj = new searchBox();
echo $userObj->autoComplete($searchWordResults);
break;
}
jQuery:
$("#searchBox").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "class/searchbox_switch.php",
dataType: "json",
data: { name_startsWith: request.term, switch_id: 1 },
success: function(data) {
response($.map(data, function(item){
return {
label: item.label,
value: item.value
};
}));
},
error: function(response) {
console.log(response.responseText);
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
searchResults(ui.item.label);
}
});
PHP (searchbox.php):
include '../dbConnect.php';
class searchBox {
public function autoComplete($name_startsWith) {
$letterSearch = $name_startsWith . "%";
$connectObj = new db_connect();
$dbh = $connectObj->connect();
$stmt = $dbh->prepare("SELECT product_name FROM products WHERE product_name LIKE :start");
$stnd = array();
$stmt->bindParam(':start', $letterSearch, PDO::PARAM_STR);
$stmt->execute();
$stnd = $stmt->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($stnd);
return $json;
}
}
OK got it. You are passing wrong key in your result. Your result data key is "product_name" And You are trying to access "label ". Try This solution:
success: function( data ) {
response( $.map( data, function(item) {
return {
label: item.product_name,
}
}));
},

Autocomplete - user typing too fast - select typed input

I have the following code for multiple autocomplete of various fields. All works fine, but the problem is that my useres type too fast and ajax do not have time to load all results. Therefore, when somebody types the whole word (which is in the suggested list, but does not appear yet - is too slow), I need to use this word so that it behaves like the used clicked at this word in the list.
The answer might be this -> How do you trigger autocomplete "select" event manually in jQueryUI?, but I have no idea how it works with filling multiple fields. Do I need to do the mysql query again after onchange? Can anybody help please? I am rather a beginner so please sorry my not-knowing. I would possibly need a guidance step by step.
If I need this - where do I put it in my code?
$(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', {item:{value:$(this).val()}});
My code is like this:
$(".addmore").on('click',function(){
count=$('table tr:visible').length;
var data="<tr><td><div class='form-control rohy'><i class='fa fa-trash-o vymazat' id='"+i+"' onclick='reply_click(this.id);calculatecelkovoucenu();removeRow(this)' value='delete_"+i+"' data-val='"+i+"' style='font-size: 18px;color: #e70000;cursor: pointer;'></i><div></td><td><div class='form-control rohy'><span id='snum"+i+"'>"+count+".</span><div></td>";
data +="<td style='padding-right: 10px;'><input class='form-control rohy' type='text' id='produktyname_"+i+"' name='produktyname_"+i+"' placeholder='Kod zbozi' ></td> <td style='padding-right: 10px;'><input class='form-control rohy' type='text' id='produkty_no_"+i+"' name='produkty_no_"+i+"' placeholder='Popis zbozi' ></td><td style='padding-right: 10px;'><input class='form-control rohy' type='text' id='phone_code_"+i+"' name='phone_code_"+i+"' placeholder='Cena za 1 ks' oninput='calculate"+i+"();calculatecelkovoucenu();'></td><td style='padding-right: 10px;'><input class='form-control rohy' type='text' id='produktypocet_"+i+"' name='produktypocet_"+i+"' placeholder='Ks' oninput='calculate"+i+"();calculatecelkovoucenu();'></td><td><input class='form-control rohy' type='text' id='celkovacena_"+i+"' name='celkovacena_"+i+"' placeholder='Celkova cena' onchange='calculate"+i+"();calculatecelkovoucenu();' readonly></td></tr>";
$('table').append(data);
row = i ;
$('#produktyname_'+i).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'getprodukty.php',
dataType: "json",
method: 'post',
delay: 0,
data: {
name_startsWith: request.term,
type: 'produkty_table',
row_num : row
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 3,
select: function( event, ui ) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#produkty_no_'+id[1]).val(names[1]);
$('#phone_code_'+id[1]).val(names[2]);
$('#produkty_code_'+id[1]).val(names[3]);
}
});
$('#produkty_code_'+i).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'getprodukty.php',
dataType: "json",
method: 'post',
delay: 0,
data: {
name_startsWith: request.term,
type: 'produkty_table',
row_num : row
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[3],
value: code[3],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 3,
select: function( event, ui ) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#produkty_no_'+id[1]).val(names[1]);
$('#phone_code_'+id[1]).val(names[2]);
$('#produktyname_'+id[1]).val(names[0]);
}
});
$('#phone_code_'+i).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'getprodukty.php',
dataType: "json",
method: 'post',
delay: 0,
data: {
name_startsWith: request.term,
type: 'produkty_table',
row_num : row
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[2],
value: code[2],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 3,
select: function( event, ui ) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#produkty_no_'+id[1]).val(names[1]);
$('#produkty_code_'+id[1]).val(names[3]);
$('#produktyname_'+id[1]).val(names[0]);
}
});
$('#produkty_no_'+i).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'getprodukty.php',
dataType: "json",
method: 'post',
delay: 0,
data: {
name_startsWith: request.term,
type: 'produkty_table',
row_num : row
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[1],
value: code[1],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 3,
select: function( event, ui ) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#produkty_code_'+id[1]).val(names[3]);
$('#phone_code_'+id[1]).val(names[2]);
$('#produktyname_'+id[1]).val(names[0]);
}
});
i++;
});
getprodukty.php is as follows:
if($_POST['type'] == 'produkty_table'){
$row_num = $_POST['row_num'];
$name = $_POST['name_startsWith'];
$query = "SELECT kod,cena,popis FROM produkty where kod LIKE '".$name."%' ORDER by kod ASC LIMIT 5";
$result = mysqli_query($spojeni, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['kod'].'|'.$row['popis'].'|'.$row['cena'].'|'.$row_num;
array_push($data, $name);
}
echo json_encode($data);
}
Thank you!
This is how I would handle it:
Store partial field value used for auto-complete
Perform ajax request
Check current value with stored value, if same proceed, if different abort (presumably the new addition has triggered a further ajax request with the newer value).

How to customize the found items in autocomplete() UI?

I am trying to change how the found items are displayed in the autocomplete UI This autoComplete wigide is used inside of a dialog box.
I tried to use the '_renderMenu' property like the code below but the found items are displayed blank "no data"
Here is my code
$("#icwsTransferTo").autocomplete({
minLength: 2,
source: function(request, response) {
$.ajax({
type: 'GET',
url: 'index.php',
data: {method: 'userSearch', term: request.term},
dataType: 'json',
cache: false,
timeout: 30000,
success: function(data) {
if(!data){
return;
}
var allFound = $.map(data, function(m) {
return {
'name': m.configurationId.displayName,
'ext': m.extension,
'id': m.configurationId.id
};
});
response(allFound);
}
});
},
select: function( event, item) {
alert(item.value + ' was selected!!!');
},
'_renderItem': function (ul, item) {
return $( "<li>" ).attr( "data-value", item.id)
.append( '<span>' + item.name+ '</span><span style="float: right"> (' + item.ext + ')</span>' )
.appendTo( ul );
}
});
I figured it out...
Here is the new code for anyone that is searching. I found this article as a great resource.
$.widget("custom.autoCompleteUserList", $.ui.autocomplete, {
_renderItem: function (ul, item ) {
if(item.ext != 'undefined' && typeof item.ext !== 'undefined'){
var label = '<div class="ui-autocpmplete-item-wrapper"><span class="ui-autocpmplete-item-name-span">' + item.name + '</span><span class="ui-autocpmplete-item-ext-span"> (ext. ' + item.ext + ')</span></div>';
} else {
var label = '<div class="ui-autocpmplete-item-wrapper">' + item.name + '</div>';
}
return $( "<li>" )
.attr( "data-value", item.id )
.append( label)
.appendTo( ul );
}
});
$("#icwsTransferTo")
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autoCompleteUserList( "instance" ).menu.active ) {
event.preventDefault();
}
}).autoCompleteUserList({
minLength: 2,
source: function(request, response) {
$.ajax({
type: 'GET',
url: 'index.php',
data: {method: 'userSearch', term: request.term},
dataType: 'json',
cache: false,
timeout: 30000,
success: function(data) {
if(!data){
return;
}
var finalSource = $.map(data, function(m) {
return {
'name': m.configurationId.displayName,
'ext': m.extension,
'id': m.configurationId.id
};
});
response(finalSource);
}
});
},
focus: function() {
// prevent value inserted on focus
//return false;
},
select: function( event, ui ) {
console.log(ui.item);
alert(ui.item.value + ' < > ' + ui.item.label + ' was selected!!!');
}
})

How make textbox readonly after filled with autocompleted value using jquery?

Here I've a textbox, its data is filled by autocomplete using JSON.
Here i want textbox readonly after selecting any value of autocomplete (suggested fields).
textbox code:
$(document).ready(function ()
{
$('#patient_id').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'opdpatientajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'patientname',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
console.log(names[1], names[2], names[3]);
$('#patientAddress').val(names[1]);
$('#patientSex').val(names[2]);
$('#patientAge').val(names[3]);
}
});
});
<input type="text" id="patient_id" name="patient_nm"
placeholder="Enter and select Mother Name" title="Please Enter and select patinet name">
$("#patientAddress").attr("disabled", "disabled");
If you want to submit the field to $_POST, you need to enable it before sending the form.
$(document).ready(function ()
{
$('#patient_id').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'opdpatientajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'patientname',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
console.log(names[1], names[2], names[3]);
$('#patientAddress').val(names[1]);
$('#patientSex').val(names[2]);
$('#patientAge').val(names[3]);
$("#patientAddress").attr("disabled", "disabled");
$("#patientSex").attr("disabled", "disabled");
$("#patientAge").attr("disabled", "disabled");
}
});
});
OR you can use this method:
$( "#other" ).click(function() {
$( "#target" ).blur();
});

jQuery autocomplete - wait until all documents loaded

I am calling multiple XML documents as source for autocomplete. I want my "loading" message to go away after all the documents have been loaded. Currently it goes away after the first is loaded.
Thanks
function callAjax(data1, url){
$.ajax({
url: url,
dataType: "xml",
success:
function(xmlResponse) {
totalrec = $("TOTALREC", xmlResponse).text();
endrec = $("ENDREC", xmlResponse).text();
var data = $("ROW", xmlResponse).map(returnResults).get(data);
$.merge(data1, data);
if(endrec<totalrec){
callAjax(data1, url + "&page_no="+ parameter++);
}
$("#_results").removeClass( "ui-autocomplete-loading" ).addClass("idleField");
$("#_results").val( "Search by Application, Keyword, Process or Name" );
$("#_results").attr( "disabled", "" );
$("#_results").autocomplete({
source: data1,
minLength: 0,
selectFirst: true,
select: function(event, ui) {
if(event.keyCode == 13){
window.open(ui.item.url);
$("#_results").blur();
}
}
})
Put the autocomplete code in an else in the if(endrec<totalrec) check.
Like so:
function callAjax(data1, url){$.ajax({
url: url,
dataType: "xml",
success:
function(xmlResponse) {
totalrec = $("TOTALREC", xmlResponse).text();
endrec = $("ENDREC", xmlResponse).text();
var data = $("ROW", xmlResponse).map(returnResults).get(data);
$.merge(data1, data);
if(endrec<totalrec){
callAjax(data1, url + "&page_no="+ parameter++);
} else {
$("#_results").removeClass( "ui-autocomplete-loading" ).addClass("idleField");
$("#_results").val( "Search by Application, Keyword, Process or Name" );
$("#_results").attr( "disabled", "" );
$("#_results").autocomplete({
source: data1,
minLength: 0,
selectFirst: true,
select: function(event, ui) {
if(event.keyCode == 13){
window.open(ui.item.url);
$("#_results").blur();
}
}
});
}
}
});

Categories

Resources