When using autocomplete, Is it possible to post above two data? - javascript

javascript
<script type="text/javascript">
function getCustomer() {
$('#CST_Idx_BI').autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: '#Url.Action("JsonGetCustomerName","Customer")',
dataType: 'JSON',
data: { Keyword: $('#CST_Idx_BI').val(), CST_Idx: $('#CST_Idx_BI').val() },
success: function (data) {
response(
$.map(data, function (item, i) {
return {
label: item.CST_Name,
value: item.CST_Idx
}
})
);
}
});
},
focus: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.question);
},
select: function (event, ui) {
$('#CST_Name_BI').val(ui.item.label);
},
})
}
</script>
When somebody inputs data(Regardless of whether numeric:CST_Inx or character:Keyword), I want to get the result they want.
But if somebody input data, Keyword = the data, CST_Idx = the data.
So I can't get any result... in my case, How can I solve this?
Is it possible to post above two data in same input element?
I mean, Regardless of whether CST_Inx or Keyword, when somebody inputs data in same input element, I want to get same result.
Umm, I've changed my post many times. In advance Sorry. I didn't check my error carefully bofore posting this. Sorry.

Related

Jquery Autocomplete not populating after error thrown

I am running a ASP.Net MVC application and using jQuery's Autocomplete in one of the textboxes to populate contract numbers after the 6th digit/character.
It is working flawlessly, until after an error is thrown for a validation check.
My code :
$(document).ready(function () {
$("#ContractNumber").autocomplete({
source: '#Url.Action("GetContractId")',
open: function () { $('ul.ui-autocomplete').hide().fadeIn() },
close: function () { $('ul.ui-autocomplete').show().fadeOut() },
minLength:6
});
});
The code that redirects to the correct controller to get the contract number is here:
$(document).ready(function () {
//$('body').on('focus', "#ContractNumber", function () {
$("#ContractNumber").autocomplete({
source: function (request, response) {
$.ajax({
url: "/PurchaseRequestDetail/GetContractId",
minLength: 1,
data: { Prefix: request.term },
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };;
}))
}
})
}
});
Here is the autocomplete that is working fine, before the error:
I wanted this autocomplete to work, on focus of the textbox, whether a validation error thrown or not.
validation error:
The code that checks for ModelState if contract number is not found :
if (contractNo is null)
{
// row.ContractId = foundList.ContractId;
db.PurchaseRequestDetail.Add(newRow);
db.SaveChanges();
}
else if (contractNo != null)
{
if (foundList is null)
{
ModelState.AddModelError("ContractNumber", "Contract Number not in the database.");
// reload the drop down lists, they don't survive the trip to the server and back
viewModel.ContractList = GetContractList(viewModel.ContractId);
return View("CreateEdit", viewModel);
}
}
Any pointers in correcting this would be helpful.
TIA.

Remove autocomplete selected item from the list in asp.net and Ajax

I am in the biggest problem
**PLEASE DONT REPORT MY QUESTION DUPLICATE BECAUSE I DID NOT GET ANSWER FOR ASP.NET IN GOOGLE.
I am using jquery Autocomplete textbox in asp.net using web service.
my code
$('input.txtE').autocomplete({
source: function (request, response) {
$.ajax({
url: "WebServices.asmx/GetNames",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txtInput' : '" + request.term + "','userName':'" + userName + "'}",
dataFilter: function (data) { return data; },
success: function (data) {
mydata = data.d;
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}))
},
error: function (result) {
alert("Error");
}
});
},
multiselect: false,
minLength: 1,
delay: 0,
select: function (e, ui) {
$(hfId).val(ui.item.val);
}
});
<input type="hidden" id="hfId"/>
And my API return data in array format
 ["Abhishek/128", "Abyss/71", "athansiah/53", "blvsian/138", "DesmondH/91", "destined2hold/62", "dnbdesigns/94", "Dvus_lotus/85", "gserranof/47", "Illusions/89", "isaacwu111/111", "js/39"]
What I need if a user selected remove him from the autocomplete list so we can't select him again.
Please help me to short out it.
Preparation
In first, you need to store setected values. It is possible by using a global variable, hidden input control or arbitrary data associated with your control. In the following example I create an array that is associated with autocomplete control and then store selected values to the array:
$('#my-control').autocomplete({
create: function( e, ui ) {
// initialize array
$(this).data('selected', []);
},
select: function( e, ui ) {
// store unique selected values
var selected = $(this).data('selected');
if(!~selected.indexOf(ui.item.value)) {
selected.push(ui.item.value);
}
},
// another options here
});
Now it is possible to consider the selected values for list filtering.
Server-side solution
The best way is to filter the list on API server side, because it reduces transferred data amount. Just send the stored values through an AJAX request, using data option:
var $control = $('#my-control');
$control.autocomplete({
source: function (request, response) {
$.ajax({
// some AJAX options
data: {
term: request.term,
selected: $control.data('selected') // send stored values
}
});
},
// some autocomplete options here
});
Then you have to implement server-side filtration in accordance to selected query string parameter.
For example
public class AutocompleteSourceController : ApiController
{
[HttpGet]
public JsonResult<IEnumerable<MyClass>> GetItems(
[FromUri]string term,
[FromUri]int[] selected)
{
// Load data
// Fliter by term substring
// Exclude selected items
// Return the result
}
}
Client-side solution
Another way is to filter responded list on client side, using success AJAX callback. In my example I will use fake online REST API server. The server ignores the term field of query string, so I also have to implement it on client-side.
$control = $('#my-input');
$control.autocomplete({
create: function(e, ui) {
$(this).data('selected', []);
},
source: function(request, response) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
var items = data
// filter by term
.filter(function(user) {
return ~user.name.toLowerCase().indexOf(request.term.toLowerCase());
})
// exclude stored selected values
.filter(function(user) {
return !~$control.data('selected').indexOf(user.id);
})
// cast to an objects with label and value properties
.map(function(user) {
return {
label: user.name,
value: user.id
}
});
response(items);
},
error: function(result) {
alert("Error");
}
});
},
multiselect: false,
minLength: 1,
delay: 0,
select: function(e, ui) {
e.preventDefault();
$ctrl = $(this);
var selected = $control.data('selected');
if (!~selected.indexOf(ui.item.value)) {
// store selected value
selected.push(ui.item.value);
// set label instead of value
$ctrl.val(ui.item.label);
}
},
});
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<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.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<input id="my-input" type="text">
Type L to the input control. The first item will be Leanne Graham, select it. Then clean the input field and type L again, there will no Leanne Graham in the dropdown menu. Select Ervin Howell, then clean the input field and type L again. There will be neither Leanne Graham nor Ervin Howell in the dropdown menu.
If you want to consider only current selected value, you could store only latest value instead of an array and modify the success callback and the select event handler.
Try to remove selected value from array using jQuery.
x = jQuery.grep(x, function(val) {return val != Item;});

jQuery autocomplete AJAX call doesn't work on 2nd match on select event

I am using autocomplete j query to suggest my users some questions and then when user select one of the questions it should shows the answer.
it works fine for the first click
when user clicks on each of these questions the answer is showing correctly but the problem is when user clear the inputs and write another word and then select one of the suggestion for the next time nothing happened after select each one
here is my jquery codes
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
dataType: 'json',
method: 'POST',
data: {
q: request.term
},
url: 'Help_And_Customer_Support/AjaxQuestion/q',
success: function (data) {
console.log(data.Qu);
response($.map(data, function (item) {
console.log(item.Ans);
return { label: item.Qu, id: item.Ans };
}))
},
});
},
select: function (event, ui) {
$("#showansw").css("height", 200);
var qans = ui.item.id;
var qq = ui.item.label;
$("#showansw p").html(qans);
$("#showansw h5").html(qq);
}
});
Appreciate any help. thanks

jquery autocomplete with ajax source does not retrieve results

I have the following autocomplete that pulls from my ajax data source:
$("#id_q").autocomplete({
source: function (request, response) {
$.ajax({
url: "/search/autocomplete/",
dataType: "jsonp",
data: {
q: request.term
},
success: function (data) {
alert(data);
response(data);
}
});
},
minLength: 3,
select: function (event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
Server side I can see that results are being returned correctly and look like:
{"results": ["BEEF", "BEEFARONI", "BEEFARONI", "BEEF", "BEET"]}
The success method never fires the alert.
Also should I rename request.term?
What am I doing wrong and where can I print the data I am returning to figure out what is going on?
Do you pass data to source method?
Is your url correct? I think yours is wrong, try writing the whole URL or use a REST client to check it.
Thanks for the hint #Andrew Whitaker . I removed the entire dataType line and it worked.

jQuery autocomplete - pass targeted element attribute as an extra parameter?

I'm using the jQuery UI Autocomplete plug-in to make an ajax call and retrieve data. As well as passing the text of the input element I'm trying to pass in the 'id' attribute of the input element as an additional parameter. An extract of my code looks like this -
$("#autocomplete input").autocomplete({
source: function(request, response) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: extractLast(request.term),
extra_param: $(this).attr('id')
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.label,
value: item.name
}
}))
}
})
},
});
The extra parameter is added to the 'data' property in the ajax call. It works okay if I specifically pass in a value e.g. '3' but I want to pass the 'id' attribute of the input element the function is being called on e.g. $(this).attr('id').
I assume it's a problem with 'this' not being evaluated in this part of the code, but I'm at a loss to see how else I can reference the element that is being targeted. Any help appreciated!
$('#autocomplete input').each(e, function() {
$(e).autocomplete('/path?param=' + $(e).attr('id'), function() { ... });
});
$('#autocomplete input').each(e, function() {
$(e).autocomplete({ source:function ... extra_param: $(e).attr('id') ... });
});
There maybe a more elegant way, but, I know autocomplete is somewhat sophisticated. I personally generate the request w/get parameters and use formatItem/formatResult instead of assigning the source to an ajax call.
I've got it working by breaking the autocomplete call out into an each. This allows me to capture the target element before I execute the autocomplete -
$("#autocomplete input").each(function() {
var that = this;
$(that).autocomplete({
source: function(request, response, this_element) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: extractLast(request.term),
extra_param: $(that).attr('id')
}
....
"Source" is the ID of your input, you receive this item and save it in the variable, "that". When the input "Source" calls the autocomplete function, you can send the value of your id stored in the variable "that" for AJAX.
Example:
<script type="text/javascript">
$(document).ready(function() {
$("#Source").each(function() {
var that = this;
var url = "<?php echo constant('URL'); ?>";
$(that).autocomplete({
source: function(request, response){
$.ajax({
url: url+"models/queries/C_getOptions.php",
dataType:"json",
data:{
word:request.term,
id : $(that).attr('id')
},
success: function(data){
response(data);
}
});
},
minLength: 1,
select: function(event,ui){
//alert("Selecciono: "+ ui.item.label);
}
});
})
});

Categories

Resources