I have a function that attaches an autocomplete to any textbox I pass into it. As you can see, in the open function, towards the end, I fill in the word for the user and select the autofilled part so that they can delete it by pressing the delete key. The problem I am having is that when I delete the autofilled/autoselected part by pressing delete, the open function runs again for some reason and autofills the word again. This behavior only happens once. If I go ahead and delete the autofilled text for a second time, the textbox stays that way.
function attachAutoComplete(id, webMethod) {
$("#" + id).autocomplete({
source: function (request, response) {
$.ajax({
url: webMethod,
data: "{ 'pre':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return { value: item }
}))
}
});
},
messages: {
noResults: '',
results: function () { }
},
minLength: 2,
open: function () {
$('.ui-autocomplete').css('width', '169px');
$('.ui-autocomplete').css('z-index', '10000');
$('.ui-autocomplete').css('list-style-type', 'none');
$('.ui-autocomplete').css('border-width', '1px');
$('.ui-autocomplete').css('border-color', '#b6b6b6');
$('.ui-autocomplete').css('border-style', 'solid');
$('.ui-autocomplete').css('background-color', '#fff');
$('.ui-autocomplete').css('padding', '0px');
$('.ui-menu-item').css('cursor', 'pointer');
var input = $(this),
firstElementText = input.data("ui-autocomplete").menu.element[0].children[0].textContent,
original = input.val();
input.val(firstElementText);
input[0].selectionStart = original.length;
input[0].selectionEnd = firstElementText.length;
},
close: function () {
var input = $(this);
var firstThreeLetters = input[0].id.substring(0, 3);
if (firstThreeLetters == "SNP") {
GetVariantsGene(input);
}
}
});
}
Thanks in advance
update: The open function only runs again if the last character that the user entered is a letter. If the last character is a number, it does not run again.
Related
I need help with an advanced search I implemented into a new existing page system.
It seems there is a problem with the existing jquery ui on the page:
<script src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript" src="js/jquery.lazy.min.js"></script>
When I enter my code the page isn't working properly anymore.
My code:
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#warenkorb_suche_feld').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#warenkorb_suche_feld').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#warenkorb_suche_feld").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
The search script works fine but I need to add
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
And after this page stops working. What can I do to get this stuff working?
Consider the following. I was not able to test it.
$(function() {
function search(term, callback) {
$('b#search-string').text(term);
$.ajax({
type: "POST",
url: "search.php",
data: {
query: term
},
cache: false,
success: function(html) {
$("ul#results").html(html);
if(callback && (typeof callback == "function")){
callback();
}
}
});
return false;
}
$('div.icon').click(function() {
$('input#warenkorb_suche_feld').focus();
});
$("input#warenkorb_suche_feld").on("keyup", function(e) {
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string.length > 0) {
$("ul#results, h4#results-text").fadeOut(400, function() {
search(search_string, function() {
$("ul#results, h4#results-text").fadeIn();
});
});
}
});
});
This makes use of the complete callback for .fadeOut(). So once it has faded, it will then run the search. I added a Callback in the search so that once the AJAX has completed, it will reveal the results with .fadeIn().
You may want to consider adjusting the length condition. This ensures
I have KendoGrid and want to detect end of all manipulations (including manipulations with html) after read(). How can I catch this event?
I have tried to use RequestEnd event with type "read", but after catching this event Kendo changes some html code in page.
Update after adding databound
I have KendoSortable, binded to KendoGrid, which contains column with positions. After position changes (onChange function), I need to block page (showLoader func) and update positions. As positions have changed, grid data (column with positions) must be reload by read(). And AFTER read() I need to unblock page by hideLoader. So, now, if I don't unbind onDataBound, my page is unblocked after remove/insert.
function onDataBound(e) {
if (ir == 0) {
updatePostion();
}
else {
hideLoader();
}
ir++;
}
function onChange(e) {
var grid = $("#TestQuestionAnswerList").data("kendoGrid");
grid.unbind("dataBound");
var newIndex = e.newIndex;
var dataItem = grid.dataSource.getByUid(e.item.data("uid"));
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
grid.bind("dataBound", onDataBound);
showLoader();
updatePostion();
}
function updatePostion() {
if (#Model.Type == 3) {
var positions = [];
grid._data.forEach(function (entry) {
positions.push(entry.ID);
});
var dataToPost = { positions: positions, questionID: #Model.ID };
$.ajax({
url: '#Url.Action("ChangePositions", "Testing")',
type: 'POST',
data: JSON.stringify(dataToPost),
datatype: 'json',
cache: false,
contentType: "application/jsonrequest; charset=utf-8",
success: function (data) {
grid.dataSource.read();
},
error: function () {
hideLoader();
alert("error");
}
});
}
else {
grid.dataSource.read();
}
}
I have a function that uses Ajax to get search results in real time, as the user types. It has a check if the input field's length is 1 or more, and if it is then it adds the class 'open' to display the dropdown for the search results. It also has an else statement, where if the length is 0 it removes open. This works fine on my localhost, but on my website if i hold backspace on more than two characters, it won't remove open (If i tap backspace it always works).
$(document).ready(function() {
$("#search").on('input', function() {
if ($('#search').val().length >= 1) {
$.ajax({
type: "POST",
url: "/url",
data: {
"json_str": $('#search').val()
},
dataType: "json",
success: function(data) {
if (!$("#searchbar").hasClass("open")) {
$("#searchbar").addClass("open")
}
if (data.length == undefined) {
$('#display').html("No results")
} else {
for (var i = 0; i < data.length; i++) {
console.log(data[i].username)
$('#display').append("<some html>")
}
}
}
});
} else {
$("#searchbar").removeClass("open")
}
});
})
I have found a solution, I am now aborting the last AJAX call if a new one is made before a response comes in.
var request = null;
$("#search").on('input', function() {
if (request){
request.abort()
}
if ($('#search').val().trim().length >= 1) {
request = $.ajax({.........
Try to trim the input value
if($('#search').val().trim().length)
I am currently using a keyup function to initiate my autosave.php file which auto saves information to a table. However, I am starting to find that the keyup seems to be inefficient due to fast typing and submitting long strings.
How can I have the ajax submit every x seconds, instead of each keyup after so many ms?
$(document).ready(function()
{
// Handle Auto Save
$('.autosaveEdit').keyup(function() {
delay(function() {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 500 );
});
});
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Solution
Use setInterval It is like setTimeout but repeats itself.
setInterval(function () {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 1000);
Optimization
turn it on when the control has focus and turn it off when focus leaves. Also poll for the form data if it has updated then send the ajax request otherwise ignore it.
var saveToken;
var save = (function () {
var form;
return function () {
var form2 = $('#ajaxForm').serialize();
if (form !== form2) { // the form has updated
form = form2;
$.ajax({
type: "post",
url: "autosave.php",
data: form,
success: function(data) {
console.log('success!');
}
});
}
}
}());
$('.autosaveEdit').focus(function() {
saveToken = setInterval(save, 1000);
});
$('.autosaveEdit').focusout(function() {
clearInterval(saveToken);
save(); // one last time
});
I believe that what you are looking for is the window.setInterval function. It's used like this:
setInterval(function() { console.log('3 seconds later!'); }, 3000);
Use setInterval
function goSaveIt()
{
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}
setInterval(goSaveIt, 5000); // 5000 for every 5 seconds
I'm trying to find out why when a user is deleted by clicking on the ajax-delete class icon and performs the deletion process it shows the gritter message after deletion however if you were to immediately delete another user afterwards it removes the previous gritter message but doesn't show another for that second deletion. Any ideas on why this could be?
EDIT: I have figured out that the issue belongs to the $.gritter.removeAll(); code line. When there is another existing notification it removes it but doesn't add the next notification.
Any ideas what I should do here?
var rowToDelete = null;
var basicTable = null;
var api_url = null;
$(document).ready(function() {});
$(document).on('click', '.ajax-delete', function(e)
{
console.log(basicTable);
e.preventDefault();
//defining it like this captures and optimizing the need to cycle over the DOM more than once
//in subsequent calls to the element specifically
$elem = $(this);
$parentElem = $elem.closest('tr');
rowToDelete = $parentElem.get(0);
api_url = $elem.attr('href');
runConfirmation($('td:eq(1)', $parentElem).text());
});
function runConfirmation(nameSting)
{
$mymodal = $('#myModal');
$('.modal-body p', $mymodal).html('Are you sure you want to delete this <strong>'+nameSting+'</strong>?');
$mymodal.modal('show');
}
$('#myModalConfirm').on('click', function(e) {
$.ajax({
type: 'post',
url: api_url,
data: { _method: 'DELETE' },
dataType: 'json',
success: function(response) {
$.gritter.removeAll();
var className = 'growl-danger';
if (response.status == "SUCCESS") {
className = 'growl-success';
basicTable.fnDeleteRow(basicTable.fnGetPosition(rowToDelete));
rowToDelete = null;
api_url = null;
}
$.gritter.add({
position: 'top-right',
fade_in_speed: 'medium',
fade_out_speed: 2000,
time: 6000,
title: response.title,
text: response.message,
class_name: className,
sticky: false
});
}
});
$('#myModal').modal('hide');
});
Replace the following line:
$.gritter.removeAll();
With
$('.gritter-item-wrapper').remove();