My autocompelete firing too many times - javascript

I am using the autocomplete here: http://blog.idealmind.com.br/geral/simple-autocomplete-jquery-plugin/
It has two problems:
1) It doesn't work the first time something is entered into textbox - not such a big problem, as you don't really want to match a single letter
2) The more irritating thing is that it fires too many times.
My javascript is here:
<script type="text/javascript">
function nameAutocomplete(field){
alert($(field).val());
$("#name").simpleAutoComplete(
'Ajax.action',
{ 'input': $(field).val(),
'_eventName': 'getObjectsByAjax'
},
function(data){
alert("we're in business");
}
);
}
</script>
The HTML looks like this:
<input type="text" name="name" id="name" size="45" class="medium-text" onkeyup="nameAutocomplete(this);"/>
This is the part of the plugin (below) that makes the Ajax call (which is working fine):
$.get(page,
{ 'input': thisElement.val(),
'_eventName': 'getObjectsByAjax'
},
function(res)
{
$('div.' + classAC).remove();
$("#autocomplete_tooltip").remove();
var r="";
var respObject=eval(res);
r+="<ul>";
for(var i in respObject)
{
r+='<li id="autocomplete_'+respObject[i].id+'"><table cellspacing=0 width="100%"><tr><td class="icon" width="20" uri="'+respObject[i].uri+'"></td><td class="caption">'+respObject[i].name+"</td></tr></table></li>";
}
r+="</ul>";
autoCompleteList = $('<div>').addClass(classAC).html(r);
I have printed the entire plugin code here:
(function($){
$.fn.extend(
{
simpleAutoComplete: function( page, options, callback ) {
if(typeof(page) == "undefined" ) {
alert("simpleAutoComplete: Você deve especificar a página que processará a consulta.");
}
var classAC = 'autocomplete';
var selClass = 'sel';
var attrCB = 'rel';
var thisElement = $(this);
$(":not(div." + classAC + ")").click(function(){
$("div." + classAC).remove();
$("#autocomplete_tooltip").remove();
});
thisElement.attr("autocomplete","off");
thisElement.keyup(function( ev )
{ var getOptions = { input: thisElement.val() }
if( typeof(options) == "object" )
{
classAC = typeof( options.autoCompleteClassName ) != "undefined" ? options.autoCompleteClassName : classAC;
selClass = typeof( options.selectedClassName ) != "undefined" ? options.selectedClassName : selClass;
attrCB = typeof( options.attrCallBack ) != "undefined" ? options.attrCallBack : attrCB;
if( typeof( options.identifier ) == "string" )
getOptions.identifier = options.identifier;
if( typeof( options.extraParamFromInput ) != "undefined" )
getOptions.extraParam = $( options.extraParamFromInput ).val();
}
kc = ( ( typeof( ev.charCode ) == 'undefined' || ev.charCode === 0 ) ? ev.keyCode : ev.charCode );
key = String.fromCharCode(kc);
console.log(kc, key, ev );
if (kc == 27)
{
$('div.' + classAC).remove();
$("#autocomplete_tooltip").remove();
}
if (kc == 13)
{
$('div.' + classAC + ' li.' + selClass).find(".caption").trigger('click');
}
if (key.match(/[a-zA-Z0-9_\- ]/) || kc == 8 || kc == 46)
{
$.get(page,
{ 'input': thisElement.val(),
'_eventName': 'getObjectsByAjax'
},
function(res)
{
$('div.' + classAC).remove();
$("#autocomplete_tooltip").remove();
var r="";
var respObject=eval(res);
r+="<ul>";
for(var i in respObject)
{
r+='<li id="autocomplete_'+respObject[i].id+'"><table cellspacing=0 width="100%"><tr><td class="icon" width="20" uri="'+respObject[i].uri+'"></td><td class="caption">'+respObject[i].name+"</td></tr></table></li>";
}
r+="</ul>";
autoCompleteList = $('<div>').addClass(classAC).html(r);
if (r != '')
{
autoCompleteList.insertAfter(thisElement);
var position = thisElement.position();
var height = thisElement.height();
var width = thisElement.width();
$('div.' + classAC).css({
'top': ( height + position.top + 6 ) + 'px',
'left': ( position.left )+'px',
'margin': '0px'
});
$('div.' + classAC + ' ul').css({
'margin-left': '0px'
});
$('div.' + classAC + ' li').each(function( n, el )
{
el = $(el);
el.mouseenter(function(){
$('div.' + classAC + ' li.' + selClass).removeClass(selClass);
$(this).addClass(selClass);
});
el.find(".caption").click(function()
{
thisElement.attr('value', el.text());
if( typeof( callback ) == "function" )
callback( el.attr(attrCB).split('_') );
$('div.' + classAC).remove();
thisElement.focus();
});
el.hover(function(e) {
urlText=$("<div>").attr("id","autocomplete_tooltip").addClass("tooltip").html($(this).find("td").attr("uri"));
urlText.css({
position:"absolute",
top:(e.pageY+20)+"px",
left:(e.pageX+20)+"px"
});
$("body").append(urlText);
},function() {
$("#autocomplete_tooltip").remove();
});
});
}
});
}
if (kc == 38 || kc == 40){
if ($('div.' + classAC + ' li.' + selClass).length == 0)
{
if (kc == 38)
{
$($('div.' + classAC + ' li')[$('div.' + classAC + ' li').length - 1]).addClass(selClass);
} else {
$($('div.' + classAC + ' li')[0]).addClass(selClass);
}
}
else
{
sel = false;
$('div.' + classAC + ' li').each(function(n, el)
{
el = $(el);
if ( !sel && el.hasClass(selClass) )
{
el.removeClass(selClass);
$($('div.' + classAC + ' li')[(kc == 38 ? (n - 1) : (n + 1))]).addClass(selClass);
sel = true;
}
});
}
}
if (thisElement.val() == '') {
$('div.' + classAC).remove();
$("#autocomplete_tooltip").remove();
}
});
}
});
})(jQuery);

Pull the part that does the ajax call into a function, and then "debounce" it like this:
var timeout = thisElement.data('timeout');
function debouncedAjax() {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(ajax, 500);
thisElement.data('timeout', timeout);
}
That way you'll be able to call debouncedAjax everywhere it now calls ajax and it will only do one call after a lull of 500ms. Adjust the timeout to taste.

I ended up using a global variable to store the setTimeout() with a call for the Ajax Function and every time a keyup happens you clear this variable and reset it with the new Ajax call, like this:
$(document).ready(function () {
// Define the global variable
$.go = null;
// Element keyup
$("#YourElementId").keyup(function() {
// Clear the global variable with the previous Ajax
clearTimeout($.go);
// Set the variable with the current Ajax call
$.go = setTimeout(function() {
FunctionThatCallsTheAjax();
},1000);
});
});
function FunctionThatCallsTheAjax(){
// Ajax Stuff Here
}
You can adjust the '1000' timeout.
It's working nice for me.

Related

JavaScript: 'i' is a type and cannot be used as an expression

I want to make dinamically javascript calculation for my form and I don't want to do this for each row. I am trying to do this with while loop, but here in my example ( i ) variable can not be recognized when I add like this:
( '<%=FV.FindControl("txt_OBR_P_1_1" + "_" & i )
<script language="javascript">
$(function () {
$(document).on("keyup", "input[type=text]", function() {
var i = 1;
while (i < 10) {
var txt_OBR_P_1_1 = parseFloat(document.getElementById('<%=FV.FindControl("txt_OBR_P_1_1" & "_" & i).ClientID%>').value.replace(/\,/g, '')) || 0
var txt_OBR_P_1_2 = parseFloat(document.getElementById('<%=FV.FindControl("txt_OBR_P_1_2" & "_" & i).ClientID%>').value.replace(/\,/g, '')) || 0
var txtKOL3 = txt_OBR_P_1_1 + txt_OBR_P_1_2;
if (txtKOL3 === 0 || txtKOL3 === Infinity || isNaN(txtKOL3)) {
txtKOL3 = $('#' + '<%:FV.FindControl("txtKOL3" & "_" & i).ClientID%>').val("");
}
else {
txtKOL3 = $('#' + '<%:FV.FindControl("txtKOL3" & "_" & i).ClientID%>').val(txtKOL3.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));
}
i++;
}
})
})
</script>

how to change function in keyCode

I would like to know that how I can change the function in the KeyCode condition?
i trying to do something but I cant get inside the keyCode.
my code:
$("body").keydown(function (e) {
// left arrow
if ((e.keyCode || e.which) == 37) {
prevpage('{!! !empty($data["previous"]) ? $data["previous"] : "4" !!}', '0');
}
// right arrow
if ((e.keyCode || e.which) == 39) {
nextpage('{!! $data["next"] !!}', '2');
}
});
thanks for all the help!.
UPDATE
this its my code for the functions nextpage and prev
function nextpage(nextpage,pagenumber) {
getCotent(nextpage,pagenumber);
var number = Number(nextpage)+1;
var numberprev = Number(nextpage)-1;
var numberpagePluss = Number(pagenumber)+1;
var numberpageMinus = Number(pagenumber)-1;
if(number == null || '{!! Request::segment(6) !!}' == '1' && numberpagePluss == '24' || '{!! Request::segment(6) !!}' == '2' && numberpagePluss == '27') {
$('.next').hide();
$('#next').hide();
} else if(numberpagePluss == '10') {
// $('#menu ul li:lt(5)').fadeOut('slow').hide();
// $('#menu ul li:gt(23)').fadeIn('slow').show();
$('#menu ul li.privie').show();
$('#menu ul li.next').show();
} else {
$('.privie').attr('onclick','prevpage('+ numberprev +',' + numberpageMinus + ')');
$('.next').attr('onclick','nextpage('+ nextpage+1 +',' + numberpagePluss + ')');
$('#privie').attr('onclick','prevpage('+ numberprev +',' + numberpageMinus + ')');
$('#next').attr('onclick','nextpage('+ nextpage+1 +',' + numberpagePluss + ')');
$('.privie').show();
$('#privie').show();
}
}
function prevpage(previd,pagenumber) {
getCotent(previd,pagenumber);
var number = Number(previd)+1;
var numberprev = Number(previd)-1;
var numberpagePluss = Number(pagenumber)+1;
var numberpageMinus = Number(pagenumber)-1;
if(numberprev == null || numberpageMinus == '0') {
$('.privie').hide();
$('#privie').hide();
} else if(numberpageMinus == '9') {
// $('#menu ul li:lt(4)').fadeIn('slow').show();
// $('#menu ul li:gt(23)').fadeOut('slow').hide();
$('#menu ul li.privie').show();
$('#menu ul li.next').show();
} else {
$('.privie').attr('onclick','prevpage('+ numberprev +')');
$('.next').attr('onclick','nextpage('+ number +')');
$('#privie').attr('onclick','prevpage('+ numberprev +')');
$('#next').attr('onclick','nextpage('+ previd+1 +')');
$('.next').show();
$('#next').show();
}
what i need its after i press left key the page its over to the next and i need the function in the keyCode will change to the next page.
Try this:
$("document").ready(function(){
$("body").keydown(function(e){
// left arrow
if ((e.keyCode || e.which) == 37)
{
console.log("condition 1");
myfun1();
}
// right arrow
if ((e.keyCode || e.which) == 39)
{
console.log("condition 2");
myfun2();
}
});
})
function myfun1(){
alert("inside myfun1");
//write your code of execution here
}
function myfun2(){
alert("inside myfun2");
//write your code of execution here
}
If it works then the keycode is running fine
try this one
var test=function(){
//your code
}
var test2=function(){
//your code
}
$("document").ready(function(){
$("body").keydown(function(e){
if ((e.keyCode || e.which) == 37)
{
test();
}
if ((e.keyCode || e.which) == 39)
{
test2();
}
});
})

i cant hide jquery autocomplete with my functions

I am creating project which it searches musics dynamicly with JSON.
Here is my html:
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class="form-control input-lg" placeholder="Search query..." id="searchquery" autocomplete="off" />
<span class="input-group-btn">
<button class="btn btn-info btn-lg" type="button" id="searchbuttonheader" onclick="search();">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
My search function called search(); ... Before I integrated jquery autocomplete I made when I click ENTER on keyboard in searchquery input it executes search(); function. To do this here is my JS code:
// ENTER KEY SEARCH //
$.fn.enterKey = function (fnc) {return this.each(function () {$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if (keycode == '13') {search();}})})
}
$("#searchquery").enterKey(function () {search();});
// ENTER KEY SEARCH //
OKAY ITS WORKING... BUT...
After integration the jquery autocomplete when I type something in searchquery input it gives some autocomplete data. Here is JS:
$('#searchquery').autoComplete({
minChars: 1,
delay: 500,
source: function(term, response){
$.getJSON('<?php echo $url_autocomplete; ?>', { query: term }, function(data){ response(data); });
},
onSelect: function(e, term, item){
search();
//alert('Item selected by '+(e.type == 'keydown' ? 'pressing enter' : 'mouse click')+'.');
}
});
When I click one of them the autocomplete hides and searches the text. But when I don't select any of them and hit enter it searches but the autocomplete is not hiding.
I WANT:
When I type something in searchquery input then I hit enter hide autocomplete suggestions and make search();.
You are not using jquery-ui-autocomplete but you use jQuery-autoComplete from Pixabay am I right? Ok, after see the code, there's no close method provided, so i add one to the original source code. You can copy and use below's jquery.auto-complete.js and call $("#searchquery").autoComplete('close'); to close the suggestion. See below example how to use it :
$("#searchquery").enterKey(function (e) {
$("#searchquery").autoComplete('close');
// .. DO YOUR SEARCH HERE ..
});
Use below's modified jquery.auto-complete.js.
/*
jQuery autoComplete v1.0.7
Copyright (c) 2014 Simon Steinberger / Pixabay
GitHub: https://github.com/Pixabay/jQuery-autoComplete
License: http://www.opensource.org/licenses/mit-license.php
*/
(function($){
$.fn.autoComplete = function(options){
var o = $.extend({}, $.fn.autoComplete.defaults, options);
// public methods
if (typeof options == 'string') {
this.each(function(){
var that = $(this);
if (options == 'destroy') {
$(window).off('resize.autocomplete', that.updateSC);
that.off('blur.autocomplete focus.autocomplete keydown.autocomplete keyup.autocomplete');
if (that.data('autocomplete'))
that.attr('autocomplete', that.data('autocomplete'));
else
that.removeAttr('autocomplete');
$(that.data('sc')).remove();
that.removeData('sc').removeData('autocomplete');
} else if (options == 'close') {
// Add new method to close the suggestion box
$(that.data('sc')).hide();
}
});
return this;
}
return this.each(function(){
var that = $(this);
// sc = 'suggestions container'
that.sc = $('<div class="autocomplete-suggestions '+o.menuClass+'"></div>');
that.data('sc', that.sc).data('autocomplete', that.attr('autocomplete'));
that.attr('autocomplete', 'off');
that.cache = {};
that.last_val = '';
that.updateSC = function(resize, next){
that.sc.css({
top: that.offset().top + that.outerHeight(),
left: that.offset().left,
width: that.outerWidth()
});
if (!resize) {
that.sc.show();
if (!that.sc.maxHeight) that.sc.maxHeight = parseInt(that.sc.css('max-height'));
if (!that.sc.suggestionHeight) that.sc.suggestionHeight = $('.autocomplete-suggestion', that.sc).first().outerHeight();
if (that.sc.suggestionHeight)
if (!next) that.sc.scrollTop(0);
else {
var scrTop = that.sc.scrollTop(), selTop = next.offset().top - that.sc.offset().top;
if (selTop + that.sc.suggestionHeight - that.sc.maxHeight > 0)
that.sc.scrollTop(selTop + that.sc.suggestionHeight + scrTop - that.sc.maxHeight);
else if (selTop < 0)
that.sc.scrollTop(selTop + scrTop);
}
}
}
$(window).on('resize.autocomplete', that.updateSC);
that.sc.appendTo('body');
that.sc.on('mouseleave', '.autocomplete-suggestion', function (){
$('.autocomplete-suggestion.selected').removeClass('selected');
});
that.sc.on('mouseenter', '.autocomplete-suggestion', function (){
$('.autocomplete-suggestion.selected').removeClass('selected');
$(this).addClass('selected');
});
that.sc.on('mousedown', '.autocomplete-suggestion', function (e){
var item = $(this), v = item.data('val');
if (v || item.hasClass('autocomplete-suggestion')) { // else outside click
that.val(v);
o.onSelect(e, v, item);
that.sc.hide();
}
return false;
});
that.on('blur.autocomplete', function(){
try { over_sb = $('.autocomplete-suggestions:hover').length; } catch(e){ over_sb = 0; } // IE7 fix :hover
if (!over_sb) {
that.last_val = that.val();
that.sc.hide();
setTimeout(function(){ that.sc.hide(); }, 350); // hide suggestions on fast input
} else if (!that.is(':focus')) setTimeout(function(){ that.focus(); }, 20);
});
if (!o.minChars) that.on('focus.autocomplete', function(){ that.last_val = '\n'; that.trigger('keyup.autocomplete'); });
function suggest(data){
var val = that.val();
that.cache[val] = data;
if (data.length && val.length >= o.minChars) {
var s = '';
for (var i=0;i<data.length;i++) s += o.renderItem(data[i], val);
that.sc.html(s);
that.updateSC(0);
}
else
that.sc.hide();
}
that.on('keydown.autocomplete', function(e){
// down (40), up (38)
if ((e.which == 40 || e.which == 38) && that.sc.html()) {
var next, sel = $('.autocomplete-suggestion.selected', that.sc);
if (!sel.length) {
next = (e.which == 40) ? $('.autocomplete-suggestion', that.sc).first() : $('.autocomplete-suggestion', that.sc).last();
that.val(next.addClass('selected').data('val'));
} else {
next = (e.which == 40) ? sel.next('.autocomplete-suggestion') : sel.prev('.autocomplete-suggestion');
if (next.length) { sel.removeClass('selected'); that.val(next.addClass('selected').data('val')); }
else { sel.removeClass('selected'); that.val(that.last_val); next = 0; }
}
that.updateSC(0, next);
return false;
}
// esc
else if (e.which == 27) that.val(that.last_val).sc.hide();
// enter or tab
else if (e.which == 13 || e.which == 9) {
var sel = $('.autocomplete-suggestion.selected', that.sc);
if (sel.length && that.sc.is(':visible')) { o.onSelect(e, sel.data('val'), sel); setTimeout(function(){ that.sc.hide(); }, 20); }
}
});
that.on('keyup.autocomplete', function(e){
if (!~$.inArray(e.which, [13, 27, 35, 36, 37, 38, 39, 40])) {
var val = that.val();
if (val.length >= o.minChars) {
if (val != that.last_val) {
that.last_val = val;
clearTimeout(that.timer);
if (o.cache) {
if (val in that.cache) { suggest(that.cache[val]); return; }
// no requests if previous suggestions were empty
for (var i=1; i<val.length-o.minChars; i++) {
var part = val.slice(0, val.length-i);
if (part in that.cache && !that.cache[part].length) { suggest([]); return; }
}
}
that.timer = setTimeout(function(){ o.source(val, suggest) }, o.delay);
}
} else {
that.last_val = val;
that.sc.hide();
}
}
});
});
}
$.fn.autoComplete.defaults = {
source: 0,
minChars: 3,
delay: 150,
cache: 1,
menuClass: '',
renderItem: function (item, search){
// escape special characters
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>';
},
onSelect: function(e, term, item){}
};
}(jQuery));

Where to place Mouse Enter and Mouse Leave in Javascript

I have the following script and am trying to add mouse enter and leave events on a slideshow such that when the mouse is over the image it won't switch to the next one, and once removed it continues.
I can get the slide to stop when the mouse is over but once the mouse is out the slideshow won't proceed.
I am unsure if these 2 lines are in the right place:
---> jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
---> jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
jQuery(function () {
jQuery('a').focus(function () {
this.blur();
});
SI.Files.stylizeAll();
slider.init();
});
---> var MOUSE_IN = false;
var slider = {
num: -1,
cur: 0,
cr: [],
al: null,
at: 10 * 1000, /* change 1000 to control speed*/
ar: true,
anim:'slide',
fade_speed:600,
init: function () {
if (!slider.data || !slider.data.length) return false;
var d = slider.data;
slider.num = d.length;
var pos = Math.floor(Math.random() * 1);
for (var i = 0; i < slider.num; i++) {
if(slider.anim == 'fade')
{
jQuery('#' + d[i].id).hide();
}
else{
jQuery('#' + d[i].id).css({
left: ((i - pos) * 1000)
});
}
jQuery('#slide-nav').append('<a id="slide-link-' + i + '" href="#" onclick="slider.slide(' + i + ');return false;" onfocus="this.blur();">' + (i + 1) + '</a>');
}
jQuery('img,div#slide-controls', jQuery('div#slide-holder')).fadeIn();
---> jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
---> jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
slider.text(d[pos]);
slider.on(pos);
if(slider.anim == 'fade')
{
slider.cur = -1;
slider.slide(0);
}
else{
slider.cur = pos;
window.setTimeout('slider.auto();', slider.at);
}
},
auto: function () {
if (!slider.ar) return false;
if(MOUSE_IN) return false;
var next = slider.cur + 1;
if (next >= slider.num) next = 0;
slider.slide(next);
},
slide: function (pos) {
if (pos < 0 || pos >= slider.num || pos == slider.cur) return;
window.clearTimeout(slider.al);
slider.al = window.setTimeout('slider.auto();', slider.at);
var d = slider.data;
if(slider.anim == 'fade')
{
for (var i = 0; i < slider.num; i++) {
if(i == slider.cur || i == pos) continue;
jQuery('#' + d[i].id).hide();
}
if(slider.cur != -1){
jQuery('#' + d[slider.cur].id).stop(false,true);
jQuery('#' + d[slider.cur].id).fadeOut(slider.fade_speed);
jQuery('#' + d[pos].id).fadeIn(slider.fade_speed);
}
else
{
jQuery('#' + d[pos].id).fadeIn(slider.fade_speed);
}
}
else
{
for (var i = 0; i < slider.num; i++)
jQuery('#' + d[i].id).stop().animate({
left: ((i - pos) * 1000)
},
1000, 'swing');
}
slider.on(pos);
slider.text(d[pos]);
slider.cur = pos;
},
on: function (pos) {
jQuery('#slide-nav a').removeClass('on');
jQuery('#slide-nav a#slide-link-' + pos).addClass('on');
},
text: function (di) {
slider.cr['a'] = di.client;
slider.cr['b'] = di.desc;
slider.ticker('#slide-client span', di.client, 0, 'a');
slider.ticker('#slide-desc', di.desc, 0, 'b');
},
ticker: function (el, text, pos, unique) {
if (slider.cr[unique] != text) return false;
ctext = text.substring(0, pos) + (pos % 2 ? '-' : '_');
jQuery(el).html(ctext);
if (pos == text.length) jQuery(el).html(text);
else window.setTimeout('slider.ticker("' + el + '","' + text + '",' + (pos + 1) + ',"' + unique + '");', 30);
}
};
if (!window.SI) {
var SI = {};
};
SI.Files = {
htmlClass: 'SI-FILES-STYLIZED',
fileClass: 'file',
wrapClass: 'cabinet',
fini: false,
able: false,
init: function () {
this.fini = true;
var ie = 0
if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) {
return;
}
this.able = true;
var html = document.getElementsByTagName('html')[0];
html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
},
stylize: function (elem) {
if (!this.fini) {
this.init();
};
if (!this.able) {
return;
};
elem.parentNode.file = elem;
elem.parentNode.onmousemove = function (e) {
if (typeof e == 'undefined') e = window.event;
if (typeof e.pageY == 'undefined' && typeof e.clientX == 'number' && document.documentElement) {
e.pageX = e.clientX + document.documentElement.scrollLeft;
e.pageY = e.clientY + document.documentElement.scrollTop;
};
var ox = oy = 0;
var elem = this;
if (elem.offsetParent) {
ox = elem.offsetLeft;
oy = elem.offsetTop;
while (elem = elem.offsetParent) {
ox += elem.offsetLeft;
oy += elem.offsetTop;
};
};
var x = e.pageX - ox;
var y = e.pageY - oy;
var w = this.file.offsetWidth;
var h = this.file.offsetHeight;
this.file.style.top = y - (h / 2) + 'px';
this.file.style.left = x - (w - 30) + 'px';
};
},
stylizeById: function (id) {
this.stylize(document.getElementById(id));
},
stylizeAll: function () {
if (!this.fini) {
this.init();
};
if (!this.able) {
return;
};
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1) this.stylize(input);
};
}
};
(function (jQuery) {
jQuery.fn.pngFix = function (settings) {
settings = jQuery.extend({
blankgif: 'blank.gif'
},
settings);
var ie55 = (navigator.appName == 'Microsoft Internet Explorer' && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf('MSIE 5.5') != -1);
var ie6 = (navigator.appName == 'Microsoft Internet Explorer' && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf('MSIE 6.0') != -1);
if (jQuery.browser.msie && (ie55 || ie6)) {
jQuery(this).each(function () {
var bgIMG = jQuery(this).css('background-image');
if (bgIMG.indexOf(".png") != -1) {
var iebg = bgIMG.split('url("')[1].split('")')[0];
jQuery(this).css('background-image', 'none');
jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='" + settings.sizingMethod + "')";
}
});
}
return jQuery;
};
})(jQuery);
jQuery(function () {
if (jQuery.browser.msie && jQuery.browser.version < 7) {
}
});
The position of both lines is fine, they just add an event handler to the mouse in/out event. The problem you experience is actually in tha auto function, if you note, at the end of the init function you have:
window.setTimeout('slider.auto();', slider.at)
This line makes a call to the auto function after a slider.at time (which is 10 seconds in your example), the auto function checks if MOUSE_IN is set to true, if it's not, then calls the slide function, then in the slide function you have another call to the auto function:
slider.al = window.setTimeout('slider.auto();', slider.at);
But once you set the MOUSE_IN variable to true the auto function simply returns and it stop the execution of further slide functions, to solve this, you may want to either handle the MOUSE_IN logic in the slide function, or before returning false in the auto function, call with a time out the auto function again.
Thought this would work but it doesnt, the mouseleave eventdoesnt seem to fire.
jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
while(MOUSE_IN==true)
{
jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
}

jQuery MultiSelect submit form on change

I am using the excellent jQuery MultiSelect plugin.
The problem I have is that I would like to submit the form when the values have changed.
Having all sorts of trouble getting this one working, does anyone have insight into how to achieve this?
Also open to alternative jQuery plugins/scripts if there are any that handle this nicely.
You could try patching jQueryMultiSelect (Untested)
Line:34 --
multiSelect: function(o, callback ) {
Line:34 ++
multiSelect: function(o, callback, postback) {
Line 221: ++
if( postback ) postback($(this));
Full Codez
if(jQuery) (function($){
$.extend($.fn, {
multiSelect: function(o, callback, postback) {
// Default options
if( !o ) var o = {};
if( o.selectAll == undefined ) o.selectAll = true;
if( o.selectAllText == undefined ) o.selectAllText = "Select All";
if( o.noneSelected == undefined ) o.noneSelected = 'Select options';
if( o.oneOrMoreSelected == undefined ) o.oneOrMoreSelected = '% selected';
// Initialize each multiSelect
$(this).each( function() {
var select = $(this);
var html = '<input type="text" readonly="readonly" class="multiSelect" value="" style="cursor: default;" />';
html += '<div class="multiSelectOptions" style="position: absolute; z-index: 99999; display: none;">';
if( o.selectAll ) html += '<label class="selectAll"><input type="checkbox" class="selectAll" />' + o.selectAllText + '</label>';
$(select).find('OPTION').each( function() {
if( $(this).val() != '' ) {
html += '<label><input type="checkbox" name="' + $(select).attr('name') + '" value="' + $(this).val() + '"';
if( $(this).attr('selected') ) html += ' checked="checked"';
html += ' />' + $(this).html() + '</label>';
}
});
html += '</div>';
$(select).after(html);
// Events
$(select).next('.multiSelect').mouseover( function() {
$(this).addClass('hover');
}).mouseout( function() {
$(this).removeClass('hover');
}).click( function() {
// Show/hide on click
if( $(this).hasClass('active') ) {
$(this).multiSelectOptionsHide();
} else {
$(this).multiSelectOptionsShow();
}
return false;
}).focus( function() {
// So it can be styled with CSS
$(this).addClass('focus');
}).blur( function() {
// So it can be styled with CSS
$(this).removeClass('focus');
});
// Determine if Select All should be checked initially
if( o.selectAll ) {
var sa = true;
$(select).next('.multiSelect').next('.multiSelectOptions').find('INPUT:checkbox').not('.selectAll').each( function() {
if( !$(this).attr('checked') ) sa = false;
});
if( sa ) $(select).next('.multiSelect').next('.multiSelectOptions').find('INPUT.selectAll').attr('checked', true).parent().addClass('checked');
}
// Handle Select All
$(select).next('.multiSelect').next('.multiSelectOptions').find('INPUT.selectAll').click( function() {
if( $(this).attr('checked') == true ) $(this).parent().parent().find('INPUT:checkbox').attr('checked', true).parent().addClass('checked'); else $(this).parent().parent().find('INPUT:checkbox').attr('checked', false).parent().removeClass('checked');
});
// Handle checkboxes
$(select).next('.multiSelect').next('.multiSelectOptions').find('INPUT:checkbox').click( function() {
$(this).parent().parent().multiSelectUpdateSelected(o);
$(this).parent().parent().find('LABEL').removeClass('checked').find('INPUT:checked').parent().addClass('checked');
$(this).parent().parent().prev('.multiSelect').focus();
if( !$(this).attr('checked') ) $(this).parent().parent().find('INPUT:checkbox.selectAll').attr('checked', false).parent().removeClass('checked');
if( callback ) callback($(this));
});
// Initial display
$(select).next('.multiSelect').next('.multiSelectOptions').each( function() {
$(this).multiSelectUpdateSelected(o);
$(this).find('INPUT:checked').parent().addClass('checked');
});
// Handle hovers
$(select).next('.multiSelect').next('.multiSelectOptions').find('LABEL').mouseover( function() {
$(this).parent().find('LABEL').removeClass('hover');
$(this).addClass('hover');
}).mouseout( function() {
$(this).parent().find('LABEL').removeClass('hover');
});
// Keyboard
$(select).next('.multiSelect').keydown( function(e) {
// Is dropdown visible?
if( $(this).next('.multiSelectOptions').is(':visible') ) {
// Dropdown is visible
// Tab
if( e.keyCode == 9 ) {
$(this).addClass('focus').trigger('click'); // esc, left, right - hide
$(this).focus().next(':input').focus();
return true;
}
// ESC, Left, Right
if( e.keyCode == 27 || e.keyCode == 37 || e.keyCode == 39 ) {
// Hide dropdown
$(this).addClass('focus').trigger('click');
}
// Down
if( e.keyCode == 40 ) {
if( !$(this).next('.multiSelectOptions').find('LABEL').hasClass('hover') ) {
// Default to first item
$(this).next('.multiSelectOptions').find('LABEL:first').addClass('hover');
} else {
// Move down, cycle to top if on bottom
$(this).next('.multiSelectOptions').find('LABEL.hover').removeClass('hover').next('LABEL').addClass('hover');
if( !$(this).next('.multiSelectOptions').find('LABEL').hasClass('hover') ) {
$(this).next('.multiSelectOptions').find('LABEL:first').addClass('hover');
}
}
return false;
}
// Up
if( e.keyCode == 38 ) {
if( !$(this).next('.multiSelectOptions').find('LABEL').hasClass('hover') ) {
// Default to first item
$(this).next('.multiSelectOptions').find('LABEL:first').addClass('hover');
} else {
// Move up, cycle to bottom if on top
$(this).next('.multiSelectOptions').find('LABEL.hover').removeClass('hover').prev('LABEL').addClass('hover');
if( !$(this).next('.multiSelectOptions').find('LABEL').hasClass('hover') ) {
$(this).next('.multiSelectOptions').find('LABEL:last').addClass('hover');
}
}
return false;
}
// Enter, Space
if( e.keyCode == 13 || e.keyCode == 32 ) {
// Select All
if( $(this).next('.multiSelectOptions').find('LABEL.hover INPUT:checkbox').hasClass('selectAll') ) {
if( $(this).next('.multiSelectOptions').find('LABEL.hover INPUT:checkbox').attr('checked') ) {
// Uncheck all
$(this).next('.multiSelectOptions').find('INPUT:checkbox').attr('checked', false).parent().removeClass('checked');
} else {
// Check all
$(this).next('.multiSelectOptions').find('INPUT:checkbox').attr('checked', true).parent().addClass('checked');
}
$(this).next('.multiSelectOptions').multiSelectUpdateSelected(o);
if( callback ) callback($(this));
return false;
}
// Other checkboxes
if( $(this).next('.multiSelectOptions').find('LABEL.hover INPUT:checkbox').attr('checked') ) {
// Uncheck
$(this).next('.multiSelectOptions').find('LABEL.hover INPUT:checkbox').attr('checked', false);
$(this).next('.multiSelectOptions').multiSelectUpdateSelected(o);
$(this).next('.multiSelectOptions').find('LABEL').removeClass('checked').find('INPUT:checked').parent().addClass('checked');
// Select all status can't be checked at this point
$(this).next('.multiSelectOptions').find('INPUT:checkbox.selectAll').attr('checked', false).parent().removeClass('checked');
if( callback ) callback($(this));
} else {
// Check
$(this).next('.multiSelectOptions').find('LABEL.hover INPUT:checkbox').attr('checked', true);
$(this).next('.multiSelectOptions').multiSelectUpdateSelected(o);
$(this).next('.multiSelectOptions').find('LABEL').removeClass('checked').find('INPUT:checked').parent().addClass('checked');
if( callback ) callback($(this));
}
}
return false;
} else {
// Dropdown is not visible
if( e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 13 || e.keyCode == 32 ) { // down, enter, space - show
// Show dropdown
$(this).removeClass('focus').trigger('click');
$(this).next('.multiSelectOptions').find('LABEL:first').addClass('hover');
return false;
}
// Tab key
if( e.keyCode == 9 ) {
// Shift focus to next INPUT element on page
$(this).focus().next(':input').focus();
return true;
}
}
// Prevent enter key from submitting form
if( e.keyCode == 13 ) return false;
});
// Eliminate the original form element
$(select).remove();
});
},
// Hide the dropdown
multiSelectOptionsHide: function() {
$(this).removeClass('active').next('.multiSelectOptions').hide();
if( postback ) postback($(this));
},
// Show the dropdown
multiSelectOptionsShow: function() {
// Hide any open option boxes
$('.multiSelect').multiSelectOptionsHide();
$(this).next('.multiSelectOptions').find('LABEL').removeClass('hover');
$(this).addClass('active').next('.multiSelectOptions').show();
// Position it
var offset = $(this).offset();
$(this).next('.multiSelectOptions').css({ top: offset.top + $(this).outerHeight() + 'px' });
$(this).next('.multiSelectOptions').css({ left: offset.left + 'px' });
// Disappear on hover out
multiSelectCurrent = $(this);
var timer = '';
$(this).next('.multiSelectOptions').hover( function() {
clearTimeout(timer);
}, function() {
timer = setTimeout('$(multiSelectCurrent).multiSelectOptionsHide(); $(multiSelectCurrent).unbind("hover");', 250);
});
},
// Update the textbox with the total number of selected items
multiSelectUpdateSelected: function(o) {
var i = 0, s = '';
$(this).find('INPUT:checkbox:checked').not('.selectAll').each( function() {
i++;
})
if( i == 0 ) {
$(this).prev('INPUT.multiSelect').val( o.noneSelected );
} else {
if( o.oneOrMoreSelected == '*' ) {
var display = '';
$(this).find('INPUT:checkbox:checked').each( function() {
if( $(this).parent().text() != o.selectAllText ) display = display + $(this).parent().text() + ', ';
});
display = display.substr(0, display.length - 2);
$(this).prev('INPUT.multiSelect').val( display );
} else {
$(this).prev('INPUT.multiSelect').val( o.oneOrMoreSelected.replace('%', i) );
}
}
}
});
})(jQuery);
K, if running in to problems because you are trying to get the value for a ASP.NET postback you can try this. It is a bit of a hack but change line in the renderOption function:
var html = '<label><input type="checkbox" name="' + id + '[]" value="' + option.value + '"';
to:
var html = '<label><input type="checkbox" name="' + id.replace(/_/g,"$") + '" value="' + option.value + '"';
Have you tried attaching it directly to the multiselect callback?
$(document).ready( function() {
$("#control_id").multiSelect(options, function() {
$('#myFormId').submit();
});
});
First I did save the selected item in an hiddenfield and after post back I assigned these checked items in an comma separated format. I wrote a document.ready() function like the one below to check the value of the selected to the dropdownlist:
var Quali = document.getElementById('<%=hdCommaList.ClientID%>').value;
var qualiList = Quali.split(',');
for (var dx = 0; dx < qualiList.length; dx++) {
if (!(qualiList[dx] == '')) {
$('input[type="checkbox"][value="' + qualiList[dx] + '"]').attr('checked', true).trigger('click').attr('checked', true);
}
}

Categories