Jquery autocomplete and enter key pressed - javascript

I have a jQuery autocomplete which reads from a database.
Everything works well, but when I press enter I need to go the database and check if the entered text exists in the table so I can select it - else I will alert invalid input.
My Attempt
I implemented the source and select method and also implemented the onkeypress method of the textbox. I am getting the result I need but even after I press enter the autocomplete is still searching for the values from the database.
How do I stop this because it is slowing my page.
Code:
$("#<%=txtSearch_Doc.ClientID%>").autocomplete({
delay:1000,
source: function (request, response) {
var m_Subtype = $("#<%=hdn_Subtype_Doc.ClientID%>").val();
var m_ConSocStr = $("#<%=hdn_ConSocStr_Doc.ClientID%>").val();
var jsonObjects = { "prefixText": request.term, "m_Subtype": m_Subtype, "m_ConSocStr": m_ConSocStr };
var jsonString = JSON.stringify(jsonObjects);
$.ajax({
url: '<%=ResolveUrl("AutoCompleteForFile.asmx/AutoSelectDoc")%>',
data: jsonString,
dataType: "json",
delay: 0,
autoFocus: true,
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('|')[0],//show key
val: item.split('|')[1], //documentnumber
}
}))
}
,
error: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
},
failure: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
}
});
},
//begin select event
select: function (e, i) {
$("#<%=hdn_Number_Doc.ClientID%>").val(i.item.val);
$("#<%=txtSearch_Doc.ClientID%>").val(i.item.val.trim());
if (i.item.val == "") {
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
$("#<%=txtSearch_Doc.ClientID%>").val("");
}
return false;
},
//end select event
minLength: 1,
autoFocus: false //IF TRUE IT WILL SELECT THE FIRST ROW BY DEFAULT, IF FALSE IT WILL NOT SELECT THE FIRST ROW
})
//end autocomplete
//key press event to handle enter pressed added by chahid on 12-jan-2016
.keypress(function (e) {
$("#<%=hdn_key_pressed.ClientID%>").val(e.keyCode);
if (e.keyCode == 13) {
e.preventDefault();
var x = $("#<%=txtSearch_Doc.ClientID%>").val();
var m_Subtype = $("#<%=hdn_Subtype_Doc.ClientID%>").val();
var m_ConSocStr = $("#<%=hdn_ConSocStr_Doc.ClientID%>").val();
var jsonObjects = { "prefixText": x, "m_Subtype": m_Subtype, "m_ConSocStr": m_ConSocStr };
var jsonString = JSON.stringify(jsonObjects);
$("#<%=hdn_is_alert.ClientID%>").val("1");
$.ajax({
url: '<%=ResolveUrl("AutoCompleteForFile.asmx/CheckForDocExistance")%>',
data: jsonString,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (dat) {
var json = JSON.stringify(dat);
obj = JSON.parse(json);
if (obj.d == "2") { // if it is empty
$("#<%=txtSearch_Doc.ClientID%>").val("");
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
}
else {
if (obj.d.split('|')[0] == "1") {
$("#<%=txtSearch_Doc.ClientID%>").val(obj.d.split('|')[1].trim());
$("#<%=hdn_Number_Doc.ClientID%>").val(obj.d.split('|')[1]);
return false;
} else {
alert("Invalid input");
$("#<%=txtSearch_Doc.ClientID%>").val("");
$("#<%=txtSearch_Doc.ClientID%>").focus();
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
}
}
},
error: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
},
failure: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
}
});
$("#<%=txtSearch_Doc.ClientID%>").autocomplete('close');
}
})

OK I manage to found a solution : I added the search event to the autocomplete where I am checking the keypresscode and returning false when it is the enter key:
search: function (event, ui) {
var key = $("#<%=hdn_key_pressed.ClientID%>").val();
if (key == 13)
return false;
else
return true;
},

Related

How can I store the data in a variable of an ajax call and print it?

I have two files one with a login form, and one with the response content if the call is successful, it executes another one for loading buttons. What I would like to do is that inside the first call there is a field called RSociale and that inside has the name and surname of the user who logged in. How can I retrieve that field and print it in the part where the buttons are already there?
This is the ajax call to login:
function lg_controllacredenziali() {
sem_PulisciCampiObbligatori();
if ($('#password').hasClass("form-required") == false) { $('#password').addClass("form-required"); }
if ($('#password').hasClass("form-text") == false) { $('#password').addClass("form-text"); }
if ($('#user').val() == '') {
sem_ControllaCampiRichiesti();
lg_ControllaCampiText();
}
if ($('#user').hasClass("input-text") == true) { $('#user').removeClass("input-text"); }
if ($('#user').hasClass("input-user") == true) { $('#user').removeClass("input-user"); }
if ($('#password').hasClass("input-text") == true) { $('#password').removeClass("input-text"); }
if ($('#password').val() == '') {
sem_ControllaCampiRichiesti();
lg_ControllaCampiText();
} else {
jQuery.ajax({
url: sem_wsurl + 'ws_json_intra_logon',
type: 'GET',
data: {
login: $('#user').val(),
clear: 'S',
password: encodeURI($('#password').val())
},
dataType: 'jsonp',
processData: true,
success: function(json) {
if (json.Response[0].ResultCode != "000") {
lg_ControllaCampifalse();
if ($('#password').hasClass("input-false") == false) { $('#password').addClass("input-false"); }
if ($('#user').hasClass("input-false") == false) { $('#user').addClass("input-false"); }
if ($('#user').hasClass("input-required") == false) { $('#user').addClass("input-required"); }
if ($('#password').hasClass("input-required") == false) { $('#password').addClass("input-required"); }
} else {
//Setto i Cookie
sem_setCookie("wc_login",$('#user').val(),null);
sem_setCookie("wc_password",json.Response[0].Pwdcookie,null);
//lg_setCookie("wc_database",json.Response[0].Dbcookie,10);
sem_setCookie("wc_database","dbeutelia",null);
sem_setCookie("wc_header",sem_header,null);
sem_setCookie("wc_footer",sem_footer,null);
window.location.replace("sem_menu.html");
window.open(url, "_self");
}
},
error: function(error) {}
});
}
}
If the call is successful, it opens a page which in its turn makes another call to load the buttons
function CaricaCluster() {
if (sem_readCookie("wc_login") != null && sem_readCookie("wc_password") != null)
{
if (sem_readCookie("wc_login").replace(/\"/g,"") != '' && sem_readCookie("wc_password").replace(/\"/g,"") != '') {
jQuery.ajax({
url: sem_wsurl + 'ws_json_sem_cluster',
type: 'GET',
data: {
ws_login: sem_readCookie("wc_login").replace(/\"/g,""),
ws_password_type: 'C',
ws_pwd: encodeURI(sem_readCookie("wc_password").replace(/\"/g,""))
},
dataType: 'jsonp',
processData: true,
success: function(json) {
if (json.Response[0].ResultCode != "000") alert("errore");
else {
$.each(json, function() {
TblPulsanti = json.Response[0].Details;
StampaPulsanti();
});
}
},
error: function(error) {
alert("Errore");
}
});
}
}
}

Javascript show element if result is not null or hide elements if result is null

Can anybody suggest me what I'm doing wrong?
I have a div with id="profGroup-section" and have javascript function that check if integer field levelId has value or is null in database.
If levelid has a value I want to show div with id="profGroup-section", else if levelid is null then I want to hide div with id="profGroup-section".
I tried different approaches, but when levelid has value then I successfully show div, but I can't manage hide the div.
Thank You in advance...
Here is my code:
checkLevelDegree: function (serviceId) {
var levelId;
$.ajax({
url: "/Sale/GetServiceByID/",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
data: { serviceId: serviceId },
beforeSend: function () {
$("#profGroup-section").hide();
},
success: function (result) {
levelId = result;
},
complete: function () {
if (levelId === null || levelId === '') {
$("#profGroup-section").hide();
return;
}
else {
$("#profGroup-section").show();
}
},
error: function () { }
});
},

Checking Recaptcha still sends a message if false

There was a problem connecting Google Recaptcha v2. Or rather with the form. The check works fine, the error message displays, but, the message is still sent.
How can I fix this?
This is a form of feedback:
$(document).ready(function() {
$("#fast-call_submit").bind("click", function(e) {
e.preventDefault();
var form = $('#feedback_form');
var fields = form.serialize();
$.ajax({
url: form.attr('action') + '.json',
type: 'post',
data: fields,
dataType: 'json',
complete: function() {},
success: function(response) {
var v = grecaptcha.getResponse();
if (v.length == 0) {
$('.w-form-re-fail').show();
return false;
} else {
if (response.status == 'ok') {
$('.w-form-done').show();
$('.w-form-fail').hide();
form.hide();
} else {
$('.w-form-fail').show();
}
$('.w-form-re-fail').hide();
return true;
}
}
});
});
});

get the notification length depends on ReadFlag

JS:
function getJSON(){
$.ajax({
url: "getgroupednotification.json",
type: "GET",
crossDomain: true,
success:function(res){
$.each(res,function(index, value){
//console.log(res);
//console.log(value);
$.each(value.Notifications, function(index_, value_){
if(value.Source == 'CIRIS'){
var i = value.Notifications.length;
if(value_.ReadFlag != 1){
}
}
});
});
});
i want to get the notification.length if ReadFlag == 0. Im using Source == CIRIS for this example.
This is the link to my JSON
https://api.myjson.com/bins/navph
You could use something like this:
function getJSON() {
$.ajax({
url: "https://api.myjson.com/bins/navph",
type: "GET",
crossDomain: true,
success: function(res) {
var lens = res.filter(function(item) {
// filter by source
return item.Source === 'CIRIS';
}).map(function(item) {
// get only Notifications
return item.Notifications;
}).map(function(notification){
// get lengths of notifications which have at least 1 RedFlag not 0
return (notification.filter(function(item){
return item.RedFlag !== 0;
}).length)
})
console.log(lens[0]);
}
})
}
getJSON();

How to use Jquery UI in my Custom Function? (Autocomplete)

I want to create a function to simplify configuration of jQuery UI AutoComplete. Here is my function code:
(function($) {
$.fn.myAutocomplete = function() {
var cache = {};
var dataUrl = args.dataUrl;
var dataSend = args.dataItem;
$.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
$.ajax({
url: dataUrl,
dataType: "json",
type: "POST",
data: dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
}
}) (jQuery);
but when I'm using this function like:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
It's give me an error:
Uncaught ReferenceError: request is not defined
Perhaps the error is referring to request.term in
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
Sorry for the trouble, I'm not adept at using jquery. Here's the final working code.
(function($) {
$.fn.myAutocomplete = function(opt) {
var cache = {};
this.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
opt.dataSend.term = request.term;
$.ajax({
url: opt.dataUrl,
dataType: "json",
type: "POST",
data: opt.dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
return this;
}
}) (jQuery);
To use this function just write code like this:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { category: $("input#category").val() }
});
Thanks Jeffery To for sharing with me to solve this problem.. ^_^

Categories