Display unobtrusive message for jquery autocomplete field - javascript

I can't seem to find an answer for my problem. I have a simple jQuery autocomplete field and the entry is required by the model. But when I check it with the validation method it is not highlighted.
<tr>
<td>
<b style="color:red">*</b>Find User ID or Enter New:<br />
#Html.ValidationMessageFor(x=>x.UserId)
</td>
<td>
<input id="users" class="userModel" style="text-transform:uppercase" />
#Html.HiddenFor(x=>x.UserId, new { #id = "txtUserId" })
</td>
</tr>
$("#users").autocomplete({
delay: 0,
minLength: 0,
autoFocus: true,
source: function (request, response) {
$.ajax({
type: 'POST',
data: { 'data': request.term },
dataType: 'json',
url: '#Url.Action("GetAllUsers")',
success: function (data) {
response($.map(data, function (obj) {
return {
value: obj
}
}));
}
});
},
select: function (event, ui) {
neworold = "old";
$.ajax({
type: 'GET',
dataType: 'json',
url: '#Url.Action("GetUser")',
data: { userid: ui.item.label },
success: function (data) {
$("#txtUserName").val(data.UserName);
$("#ddlUserRole").val(data.UserRole);
$("#chkUserAdmin").prop("checked", data.Admin);
$("#chkUserTrans").prop("checked", data.Trans);
$("#chkUserReports").prop("checked", data.Reports);
$("#txtUserId").val(data.UserId);
},
error: function (xhr) {
var err = xhr.responseText;
alert('error');
}
});
}
}).focus(function () {
$("#users").autocomplete('search', $("#users").val());
}).blur(function () {
var keyEvent = $.Event("keydown");
keyEvent.keyCode = $.ui.keyCode.ENTER;
$(this).trigger(keyEvent);
if (neworold != "old") {
$("#txtUserId").val($("#users").val());
}
});
if (!$("#userForm").valid()) {
return false;
}

Related

how use autocomplete jquery for 3 same class

i used jqueryui autocomplete iwant be the same work for some input text
but when i use $(this).val() for send value of textbox it show error and when i use (".Degree").val() shows and send to server first textbox it incorrect
function DegreeAutoComplete() {
$(".Degree").autocomplete({
position: { my: "right top", at: "right bottom", collision: "none" },
source: function (request, response) {
var spin = $(".spinnerDegree");
spin.addClass("fa-spin fa-spinner");
$.ajax({
url: "#Url.Action("GetDegree")",
type: "POST",
dataType: "json",
data: { search: $(".Degree").val() },
success: function (data) {
spin.removeClass("fa-spin fa-spinner");
response($.map(data, function (item) {
return { label: item.PersianName, value: item.PersianName, id: item.Id };
}));
}
});
},
messages: {
noResults: '',
results: function (resultsCount) { }
},
select: function (event, ui) {
// ui.item.value contains the id of the selected label
alert($(this).val());
$(this).attr("sel", ui.item.id);
}
});
}
when i use: $(this).val();
elem.nodeName is undefined
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[elem.nodeName.toLowerCa...
how can i fix it
this refers to ajax object inside it. Save this reference before using it in inside scope.
var spin = $(".spinnerDegree");
spin.addClass("fa-spin fa-spinner");
var $that = $(this);// save reference
$.ajax({
url: "#Url.Action("
GetDegree ")",
type: "POST",
dataType: "json",
data: { search: $that.val() },//use $that var here
success: function(data) {
spin.removeClass("fa-spin fa-spinner");
response($.map(data, function(item) {
return { label: item.PersianName, value: item.PersianName, id: item.Id };
}));
}
});
EDIT:
Just checked jquery UI doc
You should use request.term thats it.
source: function(request, response) {
$.ajax({
url: "#Url.Action("GetDegree")",
type: "POST",
dataType: "json",
data: {
search: request.term
},
success: function(data) {
//....
}
});
}

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
`

Two autocomplete, on two inputs (differnet id), on same page

So I have two textfields on my page, img and lok. I want them both to have a autocomplete with data from another page that uses input-value as search string. The script that comes first in code works as it should. The next is never executed. If I changes order it works for the other input, so both works by them self. So I will have to make some function name to make them different? Here is my code:
<script>
$(function () {
$("#img").autocomplete({
minLength: 3,
source: function (request, response) {
$.ajax({
url: "q/qfolder.php",
dataType: "json",
data: {
q: $("#img").val(),
},
success: function (data) {
response(data);
}
});
},
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item);
};
});
</script>
<script>
$(function () {
$("#lok").autocomplete({
minLength: 2,
source: function (request, response) {
$.ajax({
url: "q/qlok.php",
dataType: "json",
data: {
q: $("#lok").val(),
},
success: function (data) {
response(data);
}
});
},
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item);
};
});
</script>
<input type="text" id="lok">
<input type="text" id="img">
The JSONs is one dimentional, so quiet simple responses. Have read a lot of treads that was quite similar, but none resolved my problem. Sadly I have very little experience with jQuery.
http://jsfiddle.net/c4fwycfm/2/
remove .data("autocomplete") before ._renderItem
for otpion data use this data: { q: request.term },
JQ:
$(function () {
$("#lok").autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
data: {
q: request.term
},
success: function (data) {
response(data);
}
});
},
})
._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item);
};
});
$(function () {
$("#img").autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
data: {
q: request.term
},
success: function (data) {
response(data);
}
});
},
})
._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item);
};
});
try this:-
$(document).ready(function () {
SearchImg();
SearchLok();
function SearchImg() {
$("#img").autocomplete({
minLength: 3,
source: function (request, response) {
$.ajax({
url: "q/qfolder.php",
dataType: "json",
data: {
q: $("#img").val(),
},
success: function (data) {
response(data);
}
});
},
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item);
};
}
function SearchLok(){
$("#lok").autocomplete({
minLength: 2,
source: function (request, response) {
$.ajax({
url: "q/qlok.php",
dataType: "json",
data: {
q: $("#lok").val(),
},
success: function (data) {
response(data);
}
});
},
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item);
};
}
});

When I set jquery autocomplete minLength to 0 it keeps running after the user chose an object

I am using Jquery autocomplete with ajax.
Everything works fine except when I set minLength to 0.
When I choose an element from the list, the autocomplete doesn't stop running and shows me the list again.
Here is the code:
$("#id_from").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://127.0.0.1:8000/core/get_from_cities",
dataType: "json",
data: {term: request.term},
success: function (data) {
response($.map(data.data, function (item) {
return {
label: item.value,
value: item.value
}
}));
}
});
},
minLength: 0
});
Thanks..
EDIT:
Here is the solution I came up with:
$("#id_to").focus(function() {
$( "#id_to" ).autocomplete( "enable" );
});
$("#id_ffrom").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://127.0.0.1:8000/core/get_from_cities",
dataType: "json",
data: {term: request.term},
success: function (data) {
response($.map(data.data, function (item) {
return {
label: item.city,
value: item.city,
}
}));
}
});
},
minLength: 0,
select: function (event, ui) {
$('#id_from_country').val(ui.item.country)
$("#id_ffrom").autocomplete( "disable" );
}
});

How to create generic (reusable) JavaScript autocomplete function

I now have a working JavaScript autocomplete function, thanks to help from many of you. Now I want to make the function reusable. There are three variables that need to be specified for each instance of the function, as shown below. What I don't know how to do is instantiate this function with different values for these three vars.
Here is my HTML field:
<div class="ui-widget">
Text or Value:
<input type="text" id="dotmatch" />
</div>
And here is the JavaScript code which I want to keep in its own .js file:
var matchFieldName = 'dotmatch';
var resultFieldName = 'dotnumber';
var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList";
$(function() {
$('#' + matchFieldName).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
label: item.Label + "(" + item.Value+ ")",
value: item.Value
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
return ui.item.label;
}
});
});
insin was close. The solution I worked out this morning is;
function AutoComplete(matchFieldName, resultFieldName, lookupURL) {
$('#' + matchFieldName).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
value: item.Value,
label: (item.Label == item.Value) ? item.Label : item.Label + "(" + item.Value + ")"
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
}
});
}
On the web page:
<div id="AutoSuggest">
DOT Job Title or Number:
<input type="text" id="dotmatch" style="width:300px;" />
</div>
And on the web page, after the tag:
<script type="text/javascript" src="js/DOTAutocomplete.js"></script>
<script type="text/javascript">
$(function() {
AutoComplete("dotmatch", "dotnumber", "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList");
});
</script>
It looks like you're using jQuery, so you might want to implement it as a plugin.
(function($) {
$.fn.bobsAutocomplete = function(resultFieldName, lookupURL) {
this.autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: lookupURL,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({prefixText: request.term, count: 20}),
success: function(data) {
var output = jQuery.parseJSON(data.d);
response($.map(output, function(item) {
return {
label: item.Label + "(" + item.Value+ ")",
value: item.Value
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function(event, ui) {
$('#' + resultFieldName).val(ui.item.value);
return ui.item.label;
}
});
return this;
};
})(jQuery);
Usage:
$("#dotmatch").bobsAutocomplete("dotnumber", "/AutoSuggestJSTest/AutoSuggest.asmx/DOTList");

Categories

Resources