Jquery autocomplete runs after second key pressed? - javascript

I want to make autocomplete work on each textboxes using with an attribute "kolonadi"
When i press a key in textbox, the page alerts me "keydown enterance" but the autocomplete is not running. If I press one key more it works correctly.
How can i modify this code?
This is my dynamic input:
<input name="ctl00$MainContent$qtxt_UNVAN" type="text" id="MainContent_qtxt_UNVAN" class="textEntry2 ui-autocomplete-input" kolonadi="UNVAN" style="width:200px;" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
This is jquery autocomplete:
$('.textEntry2').keydown(function () {
alert("keydown enterance");
var kolonadi_ = $(this).attr("kolonadi");
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/AutoCom.asmx/GetValues") %>',
data: "{ 'word': '" + request.term + "','KullaniciIndexInGlob':'<%=KullaniciIndexInGlob %>','BaslikId':'<% =BaslikId %>','columnName':'" + kolonadi_ + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfCustomerId.ClientID %>").val(i.item.val);
},
minLength: 1
});
});

I want to make autocomplate each textboxes using textbox attr "kolonadi"
Then you need to make a jQuery selector that matches that attribute:
$('input[type="text"][kolonadi!=""]').each(function() {
// ...
});
...when I press a key in textbox, page alert me "keydown enterance" but autocomp not running. If I press one key more it runs!
The problem is that the jQuery UI .autocomplete method doesn't immediately bring down the drop-down like you think it does. If you call it once, it converts the input field permanently into an auto-completing field.
So what your code does is check for a keypress, and if it finds it, it turns the text field into an autocomplete. Then the second time you enter a keypress, the auto-complete handler runs and your handler runs, and it gets converted into an autocomplete again.
So just call .autocomplete directly on page load, get rid of the keydown handler, and call it done. You don't need your own key-down handler because the .autocomplete method will insert its own key-down handler.
Something like this:
var textEntry2 = $('.textEntry2');
var kolonadi_ = textEntry2.attr("kolonadi");
textEntry2.autocomplete({
source: function(request, response) {
$.ajax({
url: '<%=ResolveUrl("~/AutoCom.asmx/GetValues") %>',
data: "{ 'word': '" + request.term + "','KullaniciIndexInGlob':'<%=KullaniciIndexInGlob %>','BaslikId':'<% =BaslikId %>','columnName':'" + kolonadi_ + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function(response) {
alert(response.responseText);
},
failure: function(response) {
alert(response.responseText);
}
});
},
select: function(e, i) {
$("#<%=hfCustomerId.ClientID %>").val(i.item.val);
},
minLength: 1
});

Edit: the previous code doesn't work, it's necessary to iterate in all inputs from class textEntry2.
You must call the autocomplete in $(document).ready function, not in each keydown. Assuming that all inputs in which you want to use autocomplete are from class textEntry2, you'll need something like:
<script type="text/javascript">
$(document).ready(function(){
$('input.textEntry2').each(function() {
var kolonadi_ = $(this).attr("kolonadi");
$(this).autocomplete(/* do all stuff here */);
});
});
</script>

Related

Autocomplete adding extra spaces

Image Example
Image Example Keyboard
My auto commplete is adding extra spaces when data is selected from web services, how do i fix this?
i've tried mostly everything but isnt getting any results
Code:
https://jsfiddle.net/jz1e4tr6/1/
$(document).ready(function () {
$("#<%=TextBox1.ClientID%>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("/Normal/WebServices/AutoComplete.asmx/GetSubject")%>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
attr: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
An alternative "tweak" but not the right solution... before clicking submit in the code behind... i get the value from the textbox and into a variable. And trim the variable.

Textbox's Textchanged event not fire in chrome

i am Creating a page that search all client details...
i am also using json for autocomplete textbox with data of datatable...
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtSearch.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Service.asmx/GetCustomers") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfCustomerId.ClientID %>").val(i.item.val);
},
minLength: 1
});
});
i want to view data of that selected name on textbox on textchanged event,
their setup of textbgox looks like..`
<asp:TextBox ID="txtSearch" runat="server" AutoPostBack="True"
ontextchanged="txtSearch_TextChanged"></asp:TextBox>
That textchenged event trigger properly in mozilla, but not working in chrome,,
can anyone suggests some solution....
I would suggest calling server side's textbox onchange event after selecting a value from the autocomplete list as,
...
select: function (e, i) {
$("#<%=hfCustomerId.ClientID %>").val(i.item.val);
__doPostBack("txtSearch", "TextChanged");
},
minLength: 1
});
and remove autopostback property of that textbox as we are firing it from client side.
Or you can make an ajax call on select event and populate required data in client side itself.
` $(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
InitAutoCompl();
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
InitAutoCompl();
}
function InitAutoCompl() {
$("#<%=txtSearch.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: ''<%=ResolveUrl("~/Service.asmx/GetCustomers") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('##')[0],
val: item.split('##')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1, change: function (event, ui) { __doPostBack("txtSearch", "TextChanged"); }
});
}
and remove Autopostback="true" from TextBox
`

MVC - nothing happens on click (Jquery in view)

I want my button to do something onClick(), it has the ID btnSend. But nothing happens when I click the button which is weird and I can't figure out why.
The script is in my view for now within script tags.
$("#btnSend").click(function () {
var messageInfo = {
"Body": $("#Message").val(),
};
$.ajax({
type: "POST",
url: '/Api/Posts',
data: JSON.stringify(messageInfo),
contentType: "application/json;charset=utf-8",
processData: true,
success: function (data, status, xhr) {
alert("The result is : " + status);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
Are you sure your script is running after the page is loaded?
Put your script at the bottom of the page and give it a try.

prevent onchange event in jquery

I am using knockout with MVC in my project. when I pass viewModel on dropdown change It's getting continues ajax request to the server. How can I avoid the continues request??? any one can please help me on this???
My View
#ko.Html.DropDownList(m => m.RoomList, new { #class = "full-width", #id = "rmch" }, "Text", "Value").Value(m=>m.NoOfRooms)
Javascript
$(document).ready(function () {
$('#rmch').on("change", function (e) {
//viewModel.NoOfRooms = $(this).val();
$.ajax({
url: '#Url.Action("DropChange", "Home")',
type: 'POST',
data: ko.mapping.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
//ko.applyBindings(viewModel, document.getElementById("p_scentsFH"));
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
})
});
})
if I remove value part from the dropdownlist in the view It's working .but I need the value for the processing.
The simplest thing I can think of is to set the dropdownlist to readonly before updating it, then when you have finished adding the new items, remove the readonly attribute.
$(document).ready(function () {
$('#rmch').on("change", function (e) {
//viewModel.NoOfRooms = $(this).val();
$.ajax({
url: '#Url.Action("DropChange", "Home")',
type: 'POST',
data: ko.mapping.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
//this will disable the onchange event
$('#rmch').attr("readonly","readonly");
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
//ko.applyBindings(viewModel, document.getElementById("p_scentsFH"));
ko.mapping.fromJS(data, viewModel);
}
//this will enable the onchange event for the next time you select something.
$('#rmch').removeAttr("readonly");
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
})
});
})

jquery autocomplete display the output string

I want to have the script display each item on a list of value from a string of comma delimited set.
ex. "one,two,three,four"
On the autocomplete drop down, it should show:
one
two
three
four
However, the current code, show a list of only single char. There should be an easy way to split that list up and display the word instead of char. My javascript is a little limited, if someone can figure it out for me, I would appreciated. thanks. I have been search around and know that you should be able to override the parse function but it has to be easier than that. Also, I am using a webservice to return the string and can be delimited by anything but it needs to show the word.
If anyone knows the answer, I would appreciated...thanks
$("#CustomerID").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/customer/search.asmx/findvalue",
dataType: "json",
data: {
term: request.term
},
error: function(xhr, textStatus, errorThrown) {
alert('Error: ' + xhr.responseText);
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
alert('Select');
}
});
EDIT----------------------
Thank you to the previous poster for help answering.
It seems to be the nuances of the formatting or something.
This works:
success: function (data) {
response($.map(data, function (item) {
return item.split(",");
}));
},
Using this seems to just error out or does nothing:
success: function(data) {
response(data.split(","));
}
I even tried this, it goes through but does not result in a drop down menu:
success: function (data) {
response($.map(data, function (item) {
response(item.split(","));
}));
},
The above seem to work and displays what I want, not sure if it's efficient. If someone wants to explain why? Not sure why in some case you would need a response() and/or a return inorder for the autocomplete to work....
Try using .split() to split your string into an array of strings (an array is required as the source to the autocomplete widget).
$("#CustomerID").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/customer/search.asmx/findvalue",
dataType: "json",
data: {
term: request.term
},
error: function(xhr, textStatus, errorThrown) {
alert('Error: ' + xhr.responseText);
},
success: function(data) {
response(data.split(","));
}
});
},
minLength: 2,
select: function(event, ui) {
alert('Select');
}
});

Categories

Resources