My requirement is to show few options when user input some characters (minimum 3) in one of input field which might be added dynamically too.
I can not load data at page loading at beginning because data is huge. There is an ajax call to get that filtered data.
The issue what I am getting is Expected identifier error on page loading at line# 2. So, could you please tell what is wrong with the below code?
$(document).on('keydown.autocomplete', 'input.searchInput', function() {
source: function (request, response) { // Line # 2
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getNames.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
How about using another approach: initialize the autocomplete when you create the input:
$(function() {
// settings for each autocomplete
var autocompleteOptions = {
minLength: 3,
source: function(request, response) {
$.ajax({
type: "GET",
url: "getNames.html",
data: { name: request.term },
success: function(data) {
response(data);
}
});
}
};
// dynamically create an input and initialize autocomplete on it
function addInput() {
var $input = $("<input>", {
name: "search",
"class": "searchInput",
maxlength: "20"
});
$input
.appendTo("form#myForm")
.focus()
.autocomplete(autocompleteOptions);
};
// initialize autocomplete on first input
$("input.searchInput").autocomplete(autocompleteOptions);
$("input#addButton").click(addInput);
});
<form id="myForm" name="myForm" method="post">
<input id="addButton" type="button" value="Add an input" />
<input name="search" class="searchInput" maxlength="20" />
</form>
jsFiddle with AJAX
The method where I am adding new input field there writing below code.
function addInput(){
// Code to append new input filed next to existing one.
$("table").find('input[id=clientId]:last').autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
}
And some where in other js which will be used to all other (static) input fields below code is used.
jQuery("input.searchInput").autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
Note :- For any autocomplete requests in dynamically added input fields, AutoComplete code of addInput() function will be called.
Thanks to #Salman and this post Enabling jQuery Autocomplete on dynamically created input fields to give me an idea.
Try this.
$("#autocompleteElement").autocomplete({
source:function (data, response) {
$ajax({
url:'your/url?name='+data.term,
success:function(data){
response(data);
}
})
}
});
This code based on jquery UI autocomplete.
Related
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;});
I am unable to explain it properly,so i have added the image,please help me with this and please dont down vote.
Hi i am cloning the div on button click,and i want the auto complete box on the cloned elements also. on first element it is working fine but on cloned element the auto complete box(popup) is showing on 1st element but it should be shown on newly created textbox
following is the html code
<div class="repeatingSection">
<input id="Jobs[0].SampleType" name="Jobs[0].SampleType" type="text" class="form-control classSampleType" placeholder="Sample Name" required />
Add Job
following is the js code for cloning
function resetAttributeNames(section) {
var tags = section.find('input,button'), idx = section.index();
tags.each(function () {
var $this = $(this);
$.each(attrs, function (i, attr) {
var attr_val = $this.attr(attr);
if (attr_val) {
$this.attr(attr, attr_val.replace(/\[\d\]/,'['+(idx-5)+']'))
}
})
})
}
$('.addJob').click(function (e) {
e.preventDefault();
var lastRepeatingGroup = $('.repeatingSection').last();
var cloned = lastRepeatingGroup.clone(true)
cloned.find("input").val("");
cloned.insertAfter(lastRepeatingGroup);
resetAttributeNames(cloned)
});
and following is the code for auto completion
$(".classSampleType").click(function () {
var index = $(".classSampleType").index(this);
$("#Jobs\\["+index+"\\]\\.SampleType").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Lab/GetSampleType",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response(data);
}
})
},
messages: {
noResults: "", results: ""
}
});
});
For Reference i have added the image Reference Image
worked for me by making following changes
var cloned = lastRepeatingGroup.clone(true,false)
$(document).on('click','.classSampleType',function () {
var index = $(".classSampleType").index(this);
$("#Jobs\\["+index+"\\]\\.SampleType").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Lab/GetSampleType",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response(data);
}
})
},
messages: {
noResults: "", results: ""
}
});
});
I managed to retrieve a dynamic element ID from inside a foreach and send it to a controller this way:
#using (Html.BeginForm("DeleteConfirmed", "Gifts", FormMethod.Post, new { #class = "form-content", id = "formDiv" }))
{
foreach (var item in Model.productList)
{
<input type="button" value="Delete" onclick="DeleteButtonClicked(this)" data-assigned-id="#item.ID" />
}
}
and here's the relevant script, pointing to the controller's ActionResult method in charge for item deletion:
function DeleteButtonClicked(elem) {
var itemID = $(elem).data('assigned-id');
if (confirm('sure?')) {
window.location.href = "/Gifts/DeleteConfirmed/" + itemID;
}}
Now, this works just fine, as itemID is correctly retrieved.
As I would like to add a #Html.AntiForgeryToken() to the form, the idea is to change the MVC controller's Actionmethod into a JsonResult adding a little Ajax to the script, allowing me to pass both itemID and token.
Something like:
function DeleteButtonClicked(elem) {
event.preventDefault();
var form = $('#formDiv');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var itemID = $(elem).data('assigned-id');
if (confirm('sure?')) {
$.ajax({
type: 'POST',
datatype: 'json',
url: '#Url.Action("DeleteConfirmed", "Gifts")',
data: {
__RequestVerificationToken: token,
id: itemID
},
cache: false,
success: function (data) { window.location.href = "/Gifts/UserProfile?userID=" + data; },
error: function (data) { window.location.href = '#Url.Action("InternalServerError", "Error")'; }
});
}
dynamic }Some
but I have no idea on how to add the 'event' to the element (this => elem) in <input type="button" value="Delete" onclick="DeleteButtonClicked(this)" data-assigned-id="#item.ID" /> that I am using to identify the item inside the foreach loop, in order to pass it to the script.
Above script obviously fails as there's no 'event' (provided this would end to be the only mistake, which I'm not sure at all).
Some help is needed. Thanks in advance for your time and consideration.
What you want to do is use jQuery to create an event handler:
$('input[type="button"]').on('click', function(event) {
event.preventDefault();
var form = $('#formDiv');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var itemID = $(this).data('assigned-id');
if (confirm('sure?')) {
$.ajax({
type: 'POST',
datatype: 'json',
url: '#Url.Action("DeleteConfirmed", "Gifts")',
data: {
__RequestVerificationToken: token,
id: itemID
},
cache: false,
success: function (data) { window.location.href = "/Gifts/UserProfile?userID=" + data; },
error: function (data) { window.location.href = '#Url.Action("InternalServerError", "Error")'; }
});
}
});
Just make sure you render this script after your buttons are rendered. Preferably using the $(document).onReady technique.
Try the 'on' event handler attachment (http://api.jquery.com/on/). The outer function is shorthand for DOM ready.
$(function() {
$('.some-container').on('click', '.delete-btn', DeleteButtonClicked);
})
I've been trying to write a JavaScript program that returns Wikipedia search results. A few days ago, I got it to the point where I could see the item being searched for, as confirmed by the alert() method, but now when I call the same alert() method it just returns "undefined":
$("button").click(function(e){
var search =document.getElementById("test").innerHTML.value;
alert(search);
});
I swear that this is exactly what I had while it was working, so there must be some subtle issue elsewhere. Any help is appreciated, complete code below:
HTML:
Random
<section>
<form>
<br>
<div class="divid">
<input type="text" value='' id="test" >
<button >Search</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
JavaScript:
$(document).ready(function () {
$("button").click(function(e){
var search =document.getElementById("test").innerHTML.value;
alert(search);
});
var button = $('button');
var toSearch = '';
var searchUrl = "http://en.wikipedia.org/w/api.php"
var x="England";
input.autocomplete({
source: function (request, response) {
$.ajax({
url: searchUrl,
dataType: 'jsonp',
data: {
'action': "opensearch",
'format': "json",
'search': request.term
},
success: function (data) {
response(data[1]);
}
});
}
});
var playListURL = 'http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?';
$.getJSON(playListURL ,function(data) {
$.each(data.query.pages, function(i, item) {
//alert(item.title);
})
})
$.ajax({
//http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: "Carl Sagan", format: 'json' },
dataType: 'jsonp',
success:
function (x) {
//alert( x.query.search[0].title);
}
});
})
Use .innerHTML to get the html in a DOM element
Use .value to get the value of an input, textarea, or other form input
.innerHTML.value is not a thing.
If you are using jQuery, try this:
var search = $("#test").html();
alert(search);
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);
}
});
})
});