Passing string to javascript function results in value - javascript

Something really odd going on here, and I have gone round in circles trying to figure out what is going on...I have a couple of input boxes, with onchange events firing for them, the event being loaded with a JS function that takes the value ( name of another item ) and actions the function accordingly. Only thing is, when the value of the string arrives at the other function, it has somehow been assigned a numeric value, specifically that of the input box.
My php that helps build the form:
$filterfield = '"p_delweek"';
print "<span class='filter'>Del Week<input class='menulink spin-button' id='weekno' type='text' value='".$weekno."' onKeyUp='doFilter($filterfield)' onChange='doFilter($filterfield)' data-filtered='0'/><input type='button' value='Clear' onClick='doUnfilter()'></span>";
$filterfield = '"p_seedweek"';
print "<span class='filter'>Sow Week<input class='menulink spin-button' id='sowweekno' type='text' value='".$weekno."' onKeyUp='doFilter($filterfield)' onChange='doFilter($filterfield)' data-filtered='0'/><input type='button' value='Clear' onClick='doUnfilter()'></span>";
Resulting HTML in source:
<span class="filter">Del Week<input style="width: 50px; height: 22px;" class="menulink spin-button smartspinner" id="weekno" value="26" onkeyup='doFilter("p_delweek")' onchange='doFilter("p_delweek")' data-filtered="0" type="text"><input value="Clear" onclick="doUnfilter()" type="button"></span><span class="filter">Sow Week<input style="width: 50px; height: 22px;" class="menulink spin-button smartspinner" id="sowweekno" value="26" onkeyup='doFilter("p_seedweek")' onchange='doFilter("p_seedweek")' data-filtered="0" type="text"><input value="Clear" onclick="doUnfilter()" type="button"></span>
Javascript function that is called:
function doFilter(filterfield) {
console.log("DoFilter:"+filterfield);
var filterInfo=[
{
fieldName : filterfield,
logic : "equal",
value : Sigma.Util.getValue("weekno")
}
]
// the next lines action the filtering
var grid=Sigma.$grid("myGrid1");
console.log("filterinfo="+filterInfo);
var rowNOs=grid.applyFilter(filterInfo);
}
It all goes fine until we get to the console.log("DoFilter:"+filterfield) , which results in DoFilter:25; 25 happens to be the value of the input box.
How is it grabbing that value? How to pass the real one?

TBH — I'm not sure if I got what you're after. However, if you must call a function inline (I recommend that you don’t), you can pass a reference to the input field as parameter and make it available in the methods’s body:
<input onchange="doFilter('p_delweek', this)" type="text">
​
function doFilter(filterfield, field) {
console.log(filterfield);
// field is a reference to the input field, hence
console.log(field.value);
// will print the current value for this field
}

This is not the answer, this file is the problem:
(function($) {
$.fn.extend({
spinit: function(options) {
var settings = $.extend({ min: 0, max: 100, initValue: 0, callback: doFilter, stepInc: 1, pageInc: 10, width: 50, height: 15, btnWidth: 10, mask: '' }, options);
return this.each(function() {
var UP = 38;
var DOWN = 40;
var PAGEUP = 33;
var PAGEDOWN = 34;
var mouseCaptured = false;
var mouseIn = false;
var interval;
var direction = 'none';
var isPgeInc = false;
var value = Math.max(settings.initValue, settings.min);
var el = $(this).val(value).css('width', (settings.width) + 'px').css('height', settings.height + 'px').addClass('smartspinner');
raiseCallback(value);
if (settings.mask != '') el.val(settings.mask);
$.fn.reset = function(val) {
if (isNaN(val)) val = 0;
value = Math.max(val, settings.min);
$(this).val(value);
raiseCallback(value);
};
function setDirection(dir) {
direction = dir;
isPgeInc = false;
switch (dir) {
case 'up':
setClass('up');
break;
case 'down':
setClass('down');
break;
case 'pup':
isPgeInc = true;
setClass('up');
break;
case 'pdown':
isPgeInc = true;
setClass('down');
break;
case 'none':
setClass('');
break;
}
}
el.focusin(function() {
el.val(value);
});
el.click(function(e) {
mouseCaptured = true;
isPgeInc = false;
clearInterval(interval);
onValueChange();
});
el.mouseenter(function(e) {
el.val(value);
});
el.mousemove(function(e) {
if (e.pageX > (el.offset().left + settings.width) - settings.btnWidth - 4) {
if (e.pageY < el.offset().top + settings.height / 2)
setDirection('up');
else
setDirection('down');
}
else
setDirection('none');
});
el.mousedown(function(e) {
isPgeInc = false;
clearInterval(interval);
interval = setTimeout(onValueChange, 250);
});
el.mouseup(function(e) {
mouseCaptured = false;
isPgeInc = false;
clearInterval(interval);
});
el.mouseleave(function(e) {
setDirection('none');
if (settings.mask != '') el.val(settings.mask);
}); el.keydown(function(e) {
switch (e.which) {
case UP:
setDirection('up');
onValueChange();
break; // Arrow Up
case DOWN:
setDirection('down');
onValueChange();
break; // Arrow Down
case PAGEUP:
setDirection('pup');
onValueChange();
break; // Page Up
case PAGEDOWN:
setDirection('pdown');
onValueChange();
break; // Page Down
default:
setDirection('none');
break;
}
});
el.keyup(function(e) {
setDirection('none');
});
el.keypress(function(e) {
if (el.val() == settings.mask) el.val(value);
var sText = getSelectedText();
if (sText != '') {
sText = el.val().replace(sText, '');
el.val(sText);
}
if (e.which >= 48 && e.which <= 57) {
var temp = parseFloat(el.val() + (e.which - 48));
if (temp >= settings.min && temp <= settings.max) {
value = temp;
raiseCallback(value);
}
else {
e.preventDefault();
}
}
});
el.blur(function() {
if (settings.mask == '') {
if (el.val() == '')
el.val(settings.min);
}
else {
el.val(settings.mask);
}
});
el.bind("mousewheel", function(e) {
if (e.wheelDelta >= 120) {
setDirection('down');
onValueChange();
}
else if (e.wheelDelta <= -120) {
setDirection('up');
onValueChange();
}
e.preventDefault();
});
if (this.addEventListener) {
this.addEventListener('DOMMouseScroll', function(e) {
if (e.detail > 0) {
setDirection('down');
onValueChange();
}
else if (e.detail < 0) {
setDirection('up');
onValueChange();
}
e.preventDefault();
}, false);
}
function raiseCallback(val) {
if (settings.callback != null) settings.callback(val);
}
function getSelectedText() {
var startPos = el.get(0).selectionStart;
var endPos = el.get(0).selectionEnd;
var doc = document.selection;
if (doc && doc.createRange().text.length != 0) {
return doc.createRange().text;
} else if (!doc && el.val().substring(startPos, endPos).length != 0) {
return el.val().substring(startPos, endPos);
}
return '';
}
function setValue(a, b) {
if (a >= settings.min && a <= settings.max) {
value = b;
} el.val(value);
}
function onValueChange() {
if (direction == 'up') {
value += settings.stepInc;
if (value > settings.max) value = settings.max;
setValue(parseFloat(el.val()), value);
}
if (direction == 'down') {
value -= settings.stepInc;
if (value < settings.min) value = settings.min;
setValue(parseFloat(el.val()), value);
}
if (direction == 'pup') {
value += settings.pageInc;
if (value > settings.max) value = settings.max;
setValue(parseFloat(el.val()), value);
}
if (direction == 'pdown') {
value -= settings.pageInc;
if (value < settings.min) value = settings.min;
setValue(parseFloat(el.val()), value);
}
raiseCallback(value);
}
function setClass(name) {
el.removeClass('up').removeClass('down');
if (name != '') el.addClass(name);
}
});
}
});
})(jQuery);
Why and where does this alter the passing value of a function attached to the < INPUT > ?

Related

Show last three characters of a password with angularJS

I'm currently developping a mobile app with Ionic framework and AngularJS.
In my login page, the user's account name is loaded on his second connection (and is considered as a password field). However, this user can have multiple accounts. What I've been asked is to show the last three characters of this login.
I would have wanted to use something like a filter, but it doesn't seem to work on inputs ...
Then I've been looking into angularJS directives, and I've been struggling for a few days now, trying many things.
The main problem i'm encountering when doing something like
app.directive("editor", function(){
return {
require: "?ngModel",
scope: true,
template: "<input ng-model='value' ng-change='onChange()'>",
link: function(scope, element, attrs, ngModel){
if (!ngModel) return;
scope.onChange = function(){
/* process coded value here */
ngModel.$setViewValue(scope.value);
};
ngModel.$render = function(){
/* Or process coded value here */
scope.value = ngModel.$modelValue;
};
}
};
});
With this directive, I manage to have my controller value changed, but I would like only to have my view value changed.
I would really appreciate your help, AND your explanations !
I tried to do what you want. And it looks like I got.
Perhaps this is not a complete solution, but it works.
And I have not tested it in mobile browser and Safari.
You may need to modify it a bit.
Live example on jsfiddle.
angular.module('ExampleApp', [])
.controller('firstCtrl', function($scope) {
$scope.sampleItem = {
sampleName: "1234"
};
$scope.change = function(val) {
console.log(val);
}
})
.directive("useModel", ["SelectManager",
function(SelectManager) {
return {
restrict: "A",
scope: {
useModel: "=",
useModelReplacment: "#",
useModelCharacterShow: "=",
useChange: "&"
},
link: function(scope, elem) {
if (!angular.isDefined(scope.useModelCharacterShow))
scope.useModelCharacterShow = 0;
if (scope.useModelReplacment == undefined)
scope.useModelReplacment = "*";
if (scope.useModel == undefined)
scope.useModel = "";
else
elem.val(getMaskValue(scope.useModel));
scope.$watch('useModel', function(val) {
elem.val(getMaskValue(val));
if (scope.useChange)
scope.useChange();
})
function getMaskValue(val) {
var maskVal = "";
for (var i = 0; i < val.length; i++) {
if (scope.useModelCharacterShow > 0) {
if (i >= scope.useModelCharacterShow)
maskVal += scope.useModelReplacment;
else
maskVal += val[i];
}
if (scope.useModelCharacterShow < 0) {
if (i < val.length + scope.useModelCharacterShow)
maskVal += scope.useModelReplacment;
else
maskVal += val[i];
}
if (scope.useModelCharacterShow == 0) {
maskVal += scope.useModelReplacment;
}
}
return maskVal;
}
function onKeyPressed(event) {
if (event.ctrlKey && (event.charCode == 99 || event.charCode == 118 || event.charCode == 97 || event.charCode == 120))
return true;
var key_code = event.charCode;
var input = event.srcElement || event.target;
var ch = String.fromCharCode(key_code);
var start = SelectManager._getSelectionStart(input);
var end = SelectManager._getSelectionEnd(input);
// console.log('start end', start,end);
scope.useModel = scope.useModel.substr(0, start) + ch + scope.useModel.substr(end);
// console.log('inner value onKeyPressed', scope.useModel);
scope.$apply();
//console.log('show value onKeyPressed', maskVal);
//input.value = getMaskValue(scope.useModel);
event.returnValue = false;
SelectManager._setSelection(input, start + 1, start + 1);
return false;
}
function onKeyUp(event) {
if (event.ctrlKey && (event.charCode == 99 || event.charCode == 118 || event.charCode == 97 || event.charCode == 120))
return true;
var key_code = event.keyCode;
if (!(key_code == 13 || key_code == 27 || key_code == 8 || key_code == 46))
return true;
var input = event.srcElement || event.target;
var start = SelectManager._getSelectionStart(input);
var end = SelectManager._getSelectionEnd(input);
// console.log('start end', start,end);
if (key_code == 8 && start == end) {
start--;
}
if (key_code == 46 && start == end) {
//start++;
end++;
}
//console.log('inner value keyup', scope.useModel);
scope.useModel = scope.useModel.substr(0, start) + scope.useModel.substr(end);
//console.log('inner value keyup', scope.useModel);
scope.$apply();
//input.value = getMaskValue(scope.useModel);;
event.returnValue = false;
SelectManager._setSelection(input, start, start);
return event.returnValue;
}
function onKeyDown() {
var key_code = event.keyCode;
if (!(key_code == 13 || key_code == 27 || key_code == 8 || key_code == 46))
return true;
event.returnValue = false;
return event.returnValue;
}
function onPaste(event) {
var input = event.srcElement || event.target;
var ch = "";
if (event.type == "drop") {
event.returnValue = false;
return false
}
if (event.type == "paste")
ch = event.clipboardData.getData("text");
var start = SelectManager._getSelectionStart(input);
var end = SelectManager._getSelectionEnd(input);
// console.log('start end', start,end);
scope.useModel = scope.useModel.substr(0, start) + ch + scope.useModel.substr(end);
// console.log('inner value onKeyPressed', scope.useModel);
scope.$apply();
//input.value = getMaskValue(scope.useModel);
event.returnValue = false;
SelectManager._setSelection(input, start + ch.length, start + ch.length);
return false;
}
elem.on('keypress', onKeyPressed);
elem.on('keyup', onKeyUp);
elem.on('keydown', onKeyDown);
elem.on('paste drop', onPaste);
},
};
}
])
.service('SelectManager', function() {
return {
_getSelectionStart: function(obj) {
var p = 0;
if (obj.selectionStart) {
if (typeof(obj.selectionStart) == "number") p = obj.selectionStart;
} else if (document.selection) {
var r = document.selection.createRange().duplicate();
r.moveEnd("character", obj.value.length);
p = obj.value.lastIndexOf(r.text);
if (r.text == "") p = obj.value.length;
}
return p;
},
_getSelectionEnd: function(obj) {
var p = 0;
if (obj.selectionEnd) {
if (typeof(obj.selectionEnd) == "number") {
p = obj.selectionEnd;
}
} else if (document.selection) {
var r = document.selection.createRange().duplicate();
r.moveStart("character", -obj.value.length);
p = r.text.length;
}
return p;
},
GetXY: function(obj) {
var x = 0;
var y = 0;
while (obj.offsetParent) {
x += obj.offsetLeft;
y += obj.offsetTop;
obj = obj.offsetParent;
}
return {
X: x,
Y: y
};
},
_setSelection: function(obj, a, b) {
if (obj.setSelectionRange) {
obj.focus();
obj.setSelectionRange(a, b);
} else if (obj.createTextRange) {
var r = obj.createTextRange();
r.collapse();
r.moveStart("character", a);
r.moveEnd("character", (b - a));
r.select();
}
},
_Collapse: function(obj) {
var r = obj.createTextRange();
r.collapse();
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="firstCtrl">
use-model(first three) <input use-model="sampleItem.sampleName" use-change="change(sampleItem.sampleName)" use-Model-Character-Show="3">
<br> use-model(last three) <input use-model="sampleItem.sampleName" use-change="change(sampleItem.sampleName)" use-Model-Character-Show="-3">
<br> ng-model <input ng-model="sampleItem.sampleName">
<pre> {{sampleItem.sampleName}}</pre>
<button ng-click="sampleItem.sampleName='AAAAA'">
set AAAAA
</button>
</div>
</div>

mask work for id but not for class

hi i have a problem with my javascript code it works for input by id but i wat to use it on class element. I do not know what is i am doing wrong any idea? I paste my code
i want to mask time on my input
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
var value = $(text).val(); //text.value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
$(text).val() = ""; //text.value = "";
return;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text.val() = newValue;
//text.value = newValue;
} catch (e) { }
}
getElementById returns a single DOMElement while getElementsByClass returns an array of elements. To allow for both, you could have one function that accepts a DOMElement and two functions that find the elements, one for id and one for class:
function maska(elem, mask, evt) {
try {
var value = $(elem).val();
// blah blah, rest of the function
}
function maskById(id, mask, evt) {
var element = document.getElementById(id);
maska(element, mask, evt);
}
function maskByClass(class, mask, evt) {
var element_list = document.getElementsByClass(class);
for(var i = 0; var i < element_list.length; i++) {
maska(element_list[i], mask, evt);
}
}
But you would be better off using the jquery selector combined with .each , which always returns results as a set/array, regardless of selector type.
document.getElementById returns a single element, which your code is written to handle.
document.getElementsByClassName returns multiple elements. You need to loop over them and process them each individually.
I don't get why you use getElementsByClassName and then use jQuery features?
try $('input.' + inputName)
getElementById returns a single element, while getElementsByClassName returns a collection of elements. You need to iterate over this collection
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
for (var i = 0; i < text.length; i++) {
var value = text[i].value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
text[i].value = "";
continue;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text[i].value = newValue;
}
} catch (e) { }
}

Calling a javascript function for a particular class for a particular spinner button

I have following ui-spinner.js file, developed by some UI Developer:
(function($, undefined) {
var
// constants
active = 'ui-state-active',
hover = 'ui-state-hover',
disabled = 'ui-state-disabled',
keyCode = $.ui.keyCode,
up = keyCode.UP,
down = keyCode.DOWN,
right = keyCode.RIGHT,
left = keyCode.LEFT,
pageUp = keyCode.PAGE_UP,
pageDown = keyCode.PAGE_DOWN,
home = keyCode.HOME,
end = keyCode.END,
msie = $.browser.msie,
mouseWheelEventName = $.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel',
// namespace for events on input
eventNamespace = '.uispinner',
// only these special keys will be accepted, all others will be ignored unless CTRL or ALT are pressed
validKeys = [up, down, right, left, pageUp, pageDown, home, end, keyCode.BACKSPACE, keyCode.DELETE, keyCode.TAB],
// stores the currently focused spinner
// Note: due to oddities in the focus/blur events, this is part of a two-part system for confirming focus
// this must set to the control, and the focus variable must be true
// this is because hitting up/down arrows with mouse causes focus to change, but blur event for previous control doesn't fire
focusCtrl;
$.widget('ui.spinner', {
options: {
min: null,
max: null,
allowNull: false,
group: '',
point: '.',
prefix: '',
suffix: '',
places: null, // null causes it to detect the number of places in step
defaultStep: 1, // real value is 'step', and should be passed as such. This value is used to detect if passed value should override HTML5 attribute
largeStep: 10,
mouseWheel: true,
increment: 'slow',
className: null,
showOn: 'always',
width: 16,
upIconClass: "ui-icon-triangle-1-n",
downIconClass: "ui-icon-triangle-1-s",
format: function(num, places) {
var options = this,
regex = /(\d+)(\d{3})/,
result = ((isNaN(num) ? 0 : Math.abs(num)).toFixed(places)) + '';
for (result = result.replace('.', options.point); regex.test(result) && options.group; result=result.replace(regex, '$1'+options.group+'$2')) {};
return (num < 0 ? '-' : '') + options.prefix + result + options.suffix;
},
parse: function(val) {
var options = this;
if (options.group == '.')
val = val.replace('.', '');
if (options.point != '.')
val = val.replace(options.point, '.');
return parseFloat(val.replace(/[^0-9\-\.]/g, ''));
}
},
// * Widget fields *
// curvalue - current value
// places - currently effective number of decimal places
// oWidth - original input width (used for destroy)
// oMargin - original input right margin (used for destroy)
// counter - number of spins at the current spin speed
// incCounter - index within options.increment of the current spin speed
// selfChange - indicates that change event is being fired by the widget, so don't reprocess input value
// inputMaxLength - initial maxLength value on the input
// focused - this spinner currently has the focus
_create: function() {
// shortcuts
var self = this,
input = self.element,
type = input.attr('type');
if (!input.is('input') || ((type != 'text') && (type != 'number'))) {
console.error('Invalid target for ui.spinner');
return;
}
self._procOptions(true);
self._createButtons(input);
if (!input.is(':enabled'))
self.disable();
},
_createButtons: function(input) {
function getMargin(margin) {
// IE8 returns auto if no margin specified
return margin == 'auto' ? 0 : parseInt(margin);
}
var self = this,
options = self.options,
className = options.className,
buttonWidth = options.width,
showOn = options.showOn,
box = $.support.boxModel,
height = input.outerHeight(),
rightMargin = self.oMargin = getMargin(input.css('margin-right')), // store original width and right margin for later destroy
wrapper = self.wrapper = input.css({ width: (self.oWidth = (box ? input.width() : input.outerWidth())) - buttonWidth,
marginRight: rightMargin + buttonWidth, textAlign: 'right' })
.after('<span class="ui-spinner ui-widget"></span>').next(),
btnContainer = self.btnContainer = $(
'<div class="ui-spinner-buttons">' +
'<div class="ui-spinner-up ui-spinner-button ui-state-default ui-corner-tr"><span class="ui-icon '+options.upIconClass+'"> </span></div>' +
'<div class="ui-spinner-down ui-spinner-button ui-state-default ui-corner-br"><span class="ui-icon '+options.downIconClass+'"> </span></div>' +
'</div>'),
// object shortcuts
upButton, downButton, buttons, icons,
hoverDelay,
hoverDelayCallback,
// current state booleans
hovered, inKeyDown, inSpecialKey, inMouseDown,
// used to reverse left/right key directions
rtl = input[0].dir == 'rtl';
// apply className before doing any calculations because it could affect them
if (className) wrapper.addClass(className);
wrapper.append(btnContainer.css({ height: height, left: -buttonWidth-rightMargin,
// use offset calculation to fix vertical position in Firefox
top: (input.offset().top - wrapper.offset().top) + 'px' }));
buttons = self.buttons = btnContainer.find('.ui-spinner-button');
buttons.css({ width: buttonWidth - (box ? buttons.outerWidth() - buttons.width() : 0), height: height/2 - (box ? buttons.outerHeight() - buttons.height() : 0) });
upButton = buttons[0];
downButton = buttons[1];
// fix icon centering
icons = buttons.find('.ui-icon');
icons.css({ marginLeft: (buttons.innerWidth() - icons.width()) / 2, marginTop: (buttons.innerHeight() - icons.height()) / 2 });
// set width of btnContainer to be the same as the buttons
btnContainer.width(buttons.outerWidth());
if (showOn != 'always')
btnContainer.css('opacity', 0);
/* Event Bindings */
// bind hover events to show/hide buttons
if (showOn == 'hover' || showOn == 'both')
buttons.add(input)
.bind('mouseenter' + eventNamespace, function() {
setHoverDelay(function() {
hovered = true;
if (!self.focused || (showOn == 'hover')) // ignore focus flag if show on hover only
self.showButtons();
});
})
.bind('mouseleave' + eventNamespace, function hoverOut() {
setHoverDelay(function() {
hovered = false;
if (!self.focused || (showOn == 'hover')) // ignore focus flag if show on hover only
self.hideButtons();
});
});
buttons.hover(function() {
// ensure that both buttons have hover removed, sometimes they get left on
self.buttons.removeClass(hover);
if (!options.disabled)
$(this).addClass(hover);
}, function() {
$(this).removeClass(hover);
})
.mousedown(mouseDown)
.mouseup(mouseUp)
.mouseout(mouseUp);
if (msie)
// fixes dbl click not firing second mouse down in IE
buttons.dblclick(function() {
if (!options.disabled) {
// make sure any changes are posted
self._change();
self._doSpin((this === upButton ? 1 : -1) * options.step);
}
return false;
})
// fixes IE8 dbl click selection highlight
.bind('selectstart', function() {return false;});
input.bind('keydown' + eventNamespace, function(e) {
var dir, large, limit,
keyCode = e.keyCode; // shortcut for minimization
if (e.ctrl || e.alt) return true; // ignore these events
if (isSpecialKey(keyCode))
inSpecialKey = true;
if (inKeyDown) return false; // only one direction at a time, and suppress invalid keys
switch (keyCode) {
case up:
case pageUp:
dir = 1;
large = keyCode == pageUp;
break;
case down:
case pageDown:
dir = -1;
large = keyCode == pageDown;
break;
case right:
case left:
dir = (keyCode == right) ^ rtl ? 1 : -1;
break;
case home:
limit = self.options.min;
if (limit != null) self._setValue(limit);
return false;
case end:
limit = self.options.max;
limit = self.options.max;
if (limit != null) self._setValue(limit);
return false;
}
if (dir) { // only process if dir was set above
if (!inKeyDown && !options.disabled) {
keyDir = dir;
$(dir > 0 ? upButton : downButton).addClass(active);
inKeyDown = true;
self._startSpin(dir, large);
}
return false;
}
})
.bind('keyup' + eventNamespace, function(e) {
if (e.ctrl || e.alt) return true; // ignore these events
if (isSpecialKey(keyCode))
inSpecialKey = false;
switch (e.keyCode) {
case up:
case right:
case pageUp:
case down:
case left:
case pageDown:
buttons.removeClass(active)
self._stopSpin();
inKeyDown = false;
return false;
}
})
.bind('keypress' + eventNamespace, function(e) {
if (invalidKey(e.keyCode, e.charCode)) return false;
})
.bind('change' + eventNamespace, function() { self._change(); })
.bind('focus' + eventNamespace, function() {
function selectAll() {
self.element.select();
}
msie ? selectAll() : setTimeout(selectAll, 0); // add delay for Chrome, but breaks IE8
self.focused = true;
focusCtrl = self;
if (!hovered && (showOn == 'focus' || showOn == 'both')) // hovered will only be set if hover affects show
self.showButtons();
})
.bind('blur' + eventNamespace, function() {
self.focused = false;
if (!hovered && (showOn == 'focus' || showOn == 'both')) // hovered will only be set if hover affects show
self.hideButtons();
});
function isSpecialKey(keyCode) {
for (var i=0; i<validKeys.length; i++) // predefined list of special keys
if (validKeys[i] == keyCode) return true;
return false;
}
function invalidKey(keyCode, charCode) {
if (inSpecialKey) return false;
var ch = String.fromCharCode(charCode || keyCode),
options = self.options;
if ((ch >= '0') && (ch <= '9') || (ch == '-')) return false;
if (((self.places > 0) && (ch == options.point))
|| (ch == options.group)) return false;
return true;
}
// used to delay start of hover show/hide by 100 milliseconds
function setHoverDelay(callback) {
if (hoverDelay) {
// don't do anything if trying to set the same callback again
if (callback === hoverDelayCallback) return;
clearTimeout(hoverDelay);
}
hoverDelayCallback = callback;
hoverDelay = setTimeout(execute, 100);
function execute() {
hoverDelay = 0;
callback();
}
}
function mouseDown() {
if (!options.disabled) {
var input = self.element[0],
dir = (this === upButton ? 1 : -1);
input.focus();
input.select();
$(this).addClass(active);
inMouseDown = true;
self._startSpin(dir);
}
return false;
}
function mouseUp() {
if (inMouseDown) {
$(this).removeClass(active);
self._stopSpin();
inMouseDown = false;
}
return false;
}
},
_procOptions: function(init) {
var self = this,
input = self.element,
options = self.options,
min = options.min,
max = options.max,
step = options.step,
places = options.places,
maxlength = -1, temp;
// setup increment based on speed string
if (options.increment == 'slow')
options.increment = [{count: 1, mult: 1, delay: 250},
{count: 3, mult: 1, delay: 100},
{count: 0, mult: 1, delay: 50}];
else if (options.increment == 'fast')
options.increment = [{count: 1, mult: 1, delay: 250},
{count: 19, mult: 1, delay: 100},
{count: 80, mult: 1, delay: 20},
{count: 100, mult: 10, delay: 20},
{count: 0, mult: 100, delay: 20}];
if ((min == null) && ((temp = input.attr('min')) != null))
min = parseFloat(temp);
if ((max == null) && ((temp = input.attr('max')) != null))
max = parseFloat(temp);
if (!step && ((temp = input.attr('step')) != null))
if (temp != 'any') {
step = parseFloat(temp);
options.largeStep *= step;
}
options.step = step = step || options.defaultStep;
// Process step for decimal places if none are specified
if ((places == null) && ((temp = step + '').indexOf('.') != -1))
places = temp.length - temp.indexOf('.') - 1;
self.places = places;
if ((max != null) && (min != null)) {
// ensure that min is less than or equal to max
if (min > max) min = max;
// set maxlength based on min/max
maxlength = Math.max(Math.max(maxlength, options.format(max, places, input).length), options.format(min, places, input).length);
}
// only lookup input maxLength on init
if (init) self.inputMaxLength = input[0].maxLength;
temp = self.inputMaxLength;
if (temp > 0) {
maxlength = maxlength > 0 ? Math.min(temp, maxlength) : temp;
temp = Math.pow(10, maxlength) - 1;
if ((max == null) || (max > temp))
max = temp;
temp = -(temp + 1) / 10 + 1;
if ((min == null) || (min < temp))
min = temp;
}
if (maxlength > 0)
input.attr('maxlength', maxlength);
options.min = min;
options.max = max;
// ensures that current value meets constraints
self._change();
input.unbind(mouseWheelEventName + eventNamespace);
if (options.mouseWheel)
input.bind(mouseWheelEventName + eventNamespace, self._mouseWheel);
},
_mouseWheel: function(e) {
var self = $.data(this, 'spinner');
if (!self.options.disabled && self.focused && (focusCtrl === self)) {
// make sure changes are posted
self._change();
self._doSpin(((e.wheelDelta || -e.detail) > 0 ? 1 : -1) * self.options.step);
return false;
}
},
// sets an interval to call the _spin function
_setTimer: function(delay, dir, large) {
var self = this;
self._stopSpin();
self.timer = setInterval(fire, delay);
function fire() {
self._spin(dir, large);
}
},
// stops the spin timer
_stopSpin: function() {
if (this.timer) {
clearInterval(this.timer);
this.timer = 0;
}
},
// performs first step, and starts the spin timer if increment is set
_startSpin: function(dir, large) {
// shortcuts
var self = this,
options = self.options,
increment = options.increment;
// make sure any changes are posted
self._change();
self._doSpin(dir * (large ? self.options.largeStep : self.options.step));
if (increment && increment.length > 0) {
self.counter = 0;
self.incCounter = 0;
self._setTimer(increment[0].delay, dir, large);
}
},
// called by timer for each step in the spin
_spin: function(dir, large) {
// shortcuts
var self = this,
increment = self.options.increment,
curIncrement = increment[self.incCounter];
self._doSpin(dir * curIncrement.mult * (large ? self.options.largeStep : self.options.step));
self.counter++;
if ((self.counter > curIncrement.count) && (self.incCounter < increment.length-1)) {
self.counter = 0;
curIncrement = increment[++self.incCounter];
self._setTimer(curIncrement.delay, dir, large);
}
},
// actually spins the timer by a step
_doSpin: function(step) {
// shortcut
var self = this,
value = self.curvalue;
if (value == null)
value = (step > 0 ? self.options.min : self.options.max) || 0;
self._setValue(value + step);
},
// Parse the value currently in the field
_parseValue: function() {
var value = this.element.val();
return value ? this.options.parse(value, this.element) : null;
},
_validate: function(value) {
var options = this.options,
min = options.min,
max = options.max;
if ((value == null) && !options.allowNull)
value = this.curvalue != null ? this.curvalue : min || max || 0; // must confirm not null in case just initializing and had blank value
if ((max != null) && (value > max))
return max;
else if ((min != null) && (value < min))
return min;
else
return value;
},
_change: function() {
var self = this, // shortcut
value = self._parseValue(),
min = self.options.min,
max = self.options.max;
// don't reprocess if change was self triggered
if (!self.selfChange) {
if (isNaN(value))
value = self.curvalue;
self._setValue(value, true);
}
},
// overrides _setData to force option parsing
_setOption: function(key, value) {
$.Widget.prototype._setOption.call(this, key, value);
this._procOptions();
},
increment: function() {
this._doSpin(this.options.step);
},
decrement: function() {
this._doSpin(-this.options.step);
},
showButtons: function(immediate) {
var btnContainer = this.btnContainer.stop();
if (immediate)
btnContainer.css('opacity', 1);
else
btnContainer.fadeTo('fast', 1);
},
hideButtons: function(immediate) {
var btnContainer = this.btnContainer.stop();
if (immediate)
btnContainer.css('opacity', 0);
else
btnContainer.fadeTo('fast', 0);
this.buttons.removeClass(hover);
},
// Set the value directly
_setValue: function(value, suppressFireEvent) {
var self = this;
self.curvalue = value = self._validate(value);
self.element.val(value != null ?
self.options.format(value, self.places, self.element) :
'');
if (!suppressFireEvent) {
self.selfChange = true;
self.element.change();
self.selfChange = false;
}
},
// Set or retrieve the value
value: function(newValue) {
if (arguments.length) {
this._setValue(newValue);
// maintains chaining
return this.element;
}
return this.curvalue;
},
enable: function() {
this.buttons.removeClass(disabled);
this.element[0].disabled = false;
$.Widget.prototype.enable.call(this);
},
disable: function() {
this.buttons.addClass(disabled)
// in case hover class got left on
.removeClass(hover);
this.element[0].disabled = true;
$.Widget.prototype.disable.call(this);
},
destroy: function(target) {
this.wrapper.remove();
this.element.unbind(eventNamespace).css({ width: this.oWidth, marginRight: this.oMargin });
$.Widget.prototype.destroy.call(this);
}
});
})( jQuery );
And i have a group of 3 spinners written as:
<input type="text" id="rate"name="rate" class="spinner" value="0" />
On a click of a radio button I want this input box as well as the spinner to be disabled.
If i set the disabled="disabled" for then only input box is disabled but the spinner up button and down button works. I want that also to be disabled.
Secondly, I want this to happen to my 1 particular input box, if I change some property of spinner that happens to all the spinners which I don't want.
I've used the jQuery.ui.spinner 1.20 from GitHub and the disable option is working as you expect.
For instance in your code you can do:
$('#rate').spinner("disable"); // 'rate' is the HTML input id
Please ensure that the id of each input is different.
This will result in an input disabled as well as the spinner's buttons disabled.
Please, have a look at https://github.com/btburnett3/jquery.ui.spinner to download the latest version of this extension.

How to remove a property from an item which was added using jquery

The following jquery I am using in my jsp page for adding an autocomplete option to a text field which is having an id mytextfield.
jQuery(function(){
$("#mytextfield").autocomplete("popuppages/listall.jsp");
});
Within the same page, there are some cases in which I will have to remove this autocomplete feature from this text field. ( That is the same field will have to act as a textfield without autocomplete based on the user's inputs to previous fields and options)
Is there any way so that I could remove this newly added 'autocomplete' property from the particular item, that is from $("#mytextfield").
What actually I want to know is is there any option for removing added property
Incase anyone want to refer that autocomplete code, I have attached it below..
;(function($) {
$.fn.extend({
autocomplete: function(urlOrData, options) {
var isUrl = typeof urlOrData == "string";
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() {
new $.Autocompleter(this, options);
});
},
result: function(handler) {
return this.bind("result", handler);
},
search: function(handler) {
return this.trigger("search", [handler]);
},
flushCache: function() {
return this.trigger("flushCache");
},
setOptions: function(options){
return this.trigger("setOptions", [options]);
},
unautocomplete: function() {
return this.trigger("unautocomplete");
}
});
$.Autocompleter = function(input, options) {
var KEY = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
RETURN: 13,
ESC: 27,
COMMA: 188,
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8
};
// Create $ object for input element
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
var timeout;
var previousValue = "";
var cache = $.Autocompleter.Cache(options);
var hasFocus = 0;
var lastKeyPressCode;
var config = {
mouseDownOnSelect: false
};
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
var blockSubmit;
// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
if (blockSubmit) {
blockSubmit = false;
return false;
}
});
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
// a keypress means the input has focus
// avoids issue where input had focus before the autocomplete was applied
hasFocus = 1;
// track last key pressed
lastKeyPressCode = event.keyCode;
switch(event.keyCode) {
case KEY.UP:
event.preventDefault();
if ( select.visible() ) {
select.prev();
} else {
onChange(0, true);
}
break;
case KEY.DOWN:
event.preventDefault();
if ( select.visible() ) {
select.next();
} else {
onChange(0, true);
}
break;
case KEY.PAGEUP:
event.preventDefault();
if ( select.visible() ) {
select.pageUp();
} else {
onChange(0, true);
}
break;
case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
// matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;
case KEY.ESC:
select.hide();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function(){
// track whether the field has focus, we shouldn't process any
// results if the field no longer has focus
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
// show select when clicking in a focused field
if ( hasFocus++ > 1 && !select.visible() ) {
onChange(0, true);
}
}).bind("search", function() {
// TODO why not just specifying both arguments?
var fn = (arguments.length > 1) ? arguments[1] : null;
function findValueCallback(q, data) {
var result;
if( data && data.length ) {
for (var i=0; i < data.length; i++) {
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
result = data[i];
break;
}
}
}
if( typeof fn == "function" ) fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function(i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("flushCache", function() {
cache.flush();
}).bind("setOptions", function() {
$.extend(options, arguments[1]);
// if we've updated the data, repopulate
if ( "data" in arguments[1] )
cache.populate();
}).bind("unautocomplete", function() {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
});
function selectCurrent() {
var selected = select.selected();
if( !selected )
return false;
var v = selected.result;
previousValue = v;
if ( options.multiple ) {
var words = trimWords($input.val());
if ( words.length > 1 ) {
var seperator = options.multipleSeparator.length;
var cursorAt = $(input).selection().start;
var wordAt, progress = 0;
$.each(words, function(i, word) {
progress += word.length;
if (cursorAt <= progress) {
wordAt = i;
return false;
}
progress += seperator;
});
words[wordAt] = v;
// TODO this should set the cursor to the right position, but it gets overriden somewhere
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
v = words.join( options.multipleSeparator );
}
v += options.multipleSeparator;
}
$input.val(v);
hideResultsNow();
$input.trigger("result", [selected.data, selected.value]);
return true;
}
function onChange(crap, skipPrevCheck) {
if( lastKeyPressCode == KEY.DEL ) {
select.hide();
return;
}
var currentValue = $input.val();
if ( !skipPrevCheck && currentValue == previousValue )
return;
previousValue = currentValue;
currentValue = lastWord(currentValue);
if ( currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase)
currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
};
function trimWords(value) {
if (!value)
return [""];
if (!options.multiple)
return [$.trim(value)];
return $.map(value.split(options.multipleSeparator), function(word) {
return $.trim(value).length ? $.trim(word) : null;
});
}
function lastWord(value) {
if ( !options.multiple )
return value;
var words = trimWords(value);
if (words.length == 1)
return words[0];
var cursorAt = $(input).selection().start;
if (cursorAt == value.length) {
words = trimWords(value)
} else {
words = trimWords(value.replace(value.substring(cursorAt), ""));
}
return words[words.length - 1];
}
// fills in the input box w/the first match (assumed to be the best match)
// q: the term entered
// sValue: the first matching result
function autoFill(q, sValue){
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$(input).selection(previousValue.length, previousValue.length + sValue.length);
}
};
function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else {
$input.val( "" );
$input.trigger("result", null);
}
}
}
);
}
};
function receiveData(q, data) {
if ( data && data.length && hasFocus ) {
stopLoading();
select.display(data, q);
autoFill(q, data[0].value);
select.show();
} else {
hideResultsNow();
}
};
function request(term, success, failure) {
if (!options.matchCase)
term = term.toLowerCase();
var data = cache.load(term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param;
});
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
function stopLoading() {
$input.removeClass(options.loadingClass);
};
};
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
max: 100,
mustMatch: false,
extraParams: {},
selectFirst: true,
formatItem: function(row) { return row[0]; },
formatMatch: null,
autoFill: false,
width: 0,
multiple: false,
multipleSeparator: ", ",
highlight: function(value, term) {
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
},
scroll: true,
scrollHeight: 180
};
$.Autocompleter.Cache = function(options) {
var data = {};
var length = 0;
function matchSubset(s, sub) {
if (!options.matchCase)
s = s.toLowerCase();
var i = s.indexOf(sub);
if (options.matchContains == "word"){
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
}
if (i == -1) return false;
return i == 0 || options.matchContains;
};
function add(q, value) {
if (length > options.cacheLength){
flush();
}
if (!data[q]){
length++;
}
data[q] = value;
}
function populate(){
if( !options.data ) return false;
// track the matches
var stMatchSets = {},
nullData = 0;
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( !options.url ) options.cacheLength = 1;
// track all options for minChars = 0
stMatchSets[""] = [];
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i+1, options.data.length);
if ( value === false )
continue;
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
stMatchSets[firstChar] = [];
// if the match is a string
var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value
};
// push the current match into the set list
stMatchSets[firstChar].push(row);
// keep track of minChars zero items
if ( nullData++ < options.max ) {
stMatchSets[""].push(row);
}
};
// add the data items to the cache
$.each(stMatchSets, function(i, value) {
// increase the cache size
options.cacheLength++;
// add to the cache
add(i, value);
});
}
// populate any existing data
setTimeout(populate, 25);
function flush(){
data = {};
length = 0;
}
return {
flush: flush,
add: add,
populate: populate,
load: function(q) {
if (!options.cacheLength || !length)
return null;
/*
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/
if( !options.url && options.matchContains ){
// track all matches
var csub = [];
// loop through all the data grids for matches
for( var k in data ){
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if( k.length > 0 ){
var c = data[k];
$.each(c, function(i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}
return csub;
} else
// if the exact item exists, use it
if (data[q]){
return data[q];
} else
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function(i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
}
}
return null;
}
};
};
$.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = {
ACTIVE: "ac_over"
};
var listItems,
active = -1,
data,
term = "",
needsInit = true,
element,
list;
// Create results
function init() {
if (!needsInit)
return;
element = $("<div/>")
.hide()
.addClass(options.resultsClass)
.css("position", "absolute")
.appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover( function(event) {
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);
}
}).click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
}).mousedown(function() {
config.mouseDownOnSelect = true;
}).mouseup(function() {
config.mouseDownOnSelect = false;
});
if( options.width > 0 )
element.css("width", options.width);
needsInit = false;
}
function target(event) {
var element = event.target;
while(element && element.tagName != "LI")
element = element.parentNode;
// more fun with IE, sometimes event.target is empty, just ignore it then
if(!element)
return [];
return element;
}
function moveSelect(step) {
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function() {
offset += this.offsetHeight;
});
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if(offset < list.scrollTop()) {
list.scrollTop(offset);
}
}
};
function movePosition(step) {
active += step;
if (active < 0) {
active = listItems.size() - 1;
} else if (active >= listItems.size()) {
active = 0;
}
}
function limitNumberOfItems(available) {
return options.max && options.max < available
? options.max
: available;
}
function fillList() {
list.empty();
var max = limitNumberOfItems(data.length);
for (var i=0; i < max; i++) {
if (!data[i])
continue;
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
if ( formatted === false )
continue;
var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
$.data(li, "ac_data", data[i]);
}
listItems = list.find("li");
if ( options.selectFirst ) {
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
active = 0;
}
// apply bgiframe if available
if ( $.fn.bgiframe )
list.bgiframe();
}
return {
display: function(d, q) {
init();
data = d;
term = q;
fillList();
},
next: function() {
moveSelect(1);
},
prev: function() {
moveSelect(-1);
},
pageUp: function() {
if (active != 0 && active - 8 < 0) {
moveSelect( -active );
} else {
moveSelect(-8);
}
},
pageDown: function() {
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect( listItems.size() - 1 - active );
} else {
moveSelect(8);
}
},
hide: function() {
element && element.hide();
listItems && listItems.removeClass(CLASSES.ACTIVE);
active = -1;
},
visible : function() {
return element && element.is(":visible");
},
current: function() {
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
},
show: function() {
var offset = $(input).offset();
element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left
}).show();
if(options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function() {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
}
}
}
},
selected: function() {
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
return selected && selected.length && $.data(selected[0], "ac_data");
},
emptyList: function (){
list && list.empty();
},
unbind: function() {
element && element.remove();
}
};
};
$.fn.selection = function(start, end) {
if (start !== undefined) {
return this.each(function() {
if( this.createTextRange ){
var selRange = this.createTextRange();
if (end === undefined || start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
}
} else if( this.setSelectionRange ){
this.setSelectionRange(start, end);
} else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if ( field.createTextRange ) {
var range = document.selection.createRange(),
orig = field.value,
teststring = "<->",
textLength = range.text.length;
range.text = teststring;
var caretAt = field.value.indexOf(teststring);
field.value = orig;
this.selection(caretAt, caretAt + textLength);
return {
start: caretAt,
end: caretAt + textLength
}
} else if( field.selectionStart !== undefined ){
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
})(jQuery);
Looks like you are looking for destroy or disable method of autocomplete..
Check Documentation...
destroy
disable
$("#mytextfield").autocomplete( "destroy" )
$("#mytextfield").autocomplete( "disable" )
The difference is after destroy you cannot enable it back...but after disable by using enable you can enable it back..
You can use .removeAttr()
$(target).removeAttr('propertyName');
This will totally remove that property.
But if you want to change any property then use .prop() or .attr()

Any Good Number Picker for JQuery (or Javascript)?

Are there any good number picker for jquery (or standalone js)?
I would like a number picker where there is a max and min number that the user can choose from. Also, it have other options such as displaying odd number or even number or prime number or a range of number whereby some numbers in between are skipped.
Using a select to do this you can create an array with the numbers to skip and do a for loop to write the options:
int minNumber = 0;
int maxNumber = 10;
int[] skipThese = { 5, 7 };
for (int i = minNumber; i <= maxNumber; i++)
{
if(!skipThese.Contains(i)) Response.Write(String.Concat("<option value=\"", i, "\">", i, "</option>"));
}
You can do this with razor or any other way to output the HTML.
You can also do this with jQuery, dynamicaly, following the same idea:
$(document).ready(function() {
var minNumber = 0;
var maxNumber = 10;
var skipThese = [5, 7];
for (var i = minNumber; i <= maxNumber; i++) {
if ($.inArray(i, skipThese) == -1) $('#selectListID').append("<option value=\"" + i + "\">" + i + "</option>");
}
});
Edit:
Or you can use the C# code above in an aspx page and load it with AJAX from the page:
Create a select box in the page:
<select name="numPicker" id="numPicker">
<option>Loading...</option>
</select>
In a script in this page you could use jQuery's ajax() to fetch the data and populate the <select>:
$(document).ready(function() {
var numPickerSelect = $("#numPicker");
$.ajax({
url: 'url/to/page.aspx',
type: 'post'
success: function(data) {
numPickerSelect.find('option').remove(); // Remove the options in the select field
numPickerSelect.append(data); // Load the content generated by the server into the select field
},
error: function() {
alert('An error has ocurred!');
}
});
//Or use this (not sure if will work)
numPickerSelect.load("url/to/page.aspx");
});
I have used this. You should be able to modify to add extra options such as min and max fairly easily.
// Make a control only accept numeric input
// eg, $("#myedit").numeric()
// $("#myedit").numeric({alow: ' ,.'})
// $("#myedit").numeric({decimals: 2})
(function($) {
$.fn.alphanumeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
p = $.extend({
ichars: "!##$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
nchars: "",
allow: "",
decimals: null
}, p);
return this.each
(
function() {
if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
s = p.allow.split('');
for (i = 0; i < s.length; i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
p.allow = s.join('|');
var reg = new RegExp(p.allow, 'gi');
var ch = p.ichars + p.nchars;
ch = ch.replace(reg, '');
var dp = p.decimals;
var isInteger = function(val) {
var objRegExp = /(^-?\d\d*$)/;
return objRegExp.test(val);
};
var isNumeric = function(val) {
// If the last digit is a . then add a 0 before testing so if they type 25. it will be accepted
var lastChar = val.substring(val.length - 1);
if (lastChar == ".") val = val + "0";
var objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1," + dp + "})?|\\.\\d{1," + dp + "})\\s*$", "g");
if (dp == -1)
objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1,25})?|\\.\\d{1,25})\\s*$", "g");
var result = objRegExp.test(val);
return result;
};
$(this).blur(function(e) {
var text = $(this).val();
if (dp != null) {
if (dp == 0) {
if (!isInteger(text)) {
$(this).val('');
e.preventDefault();
}
}
else {
if (!isNumeric(text)) {
$(this).val('');
e.preventDefault();
}
}
} else {
var c = text.split('')
for (i = 0; i < text.length; i++) {
if (ch.indexOf(c[i]) != -1) {
$(this).val('');
e.preventDefault();
};
}
}
});
$(this).keypress
(
function(e) {
switch (e.which) {
//Firefox fix, for ignoring specific presses
case 8: // backspace key
return true;
case 46: // delete key
return true;
};
if (dp != null) {
if (e.which == 32) { e.preventDefault(); return false; }
var range = getRange(this);
var typed = String.fromCharCode(e.which);
var text = $(this).val().substr(0, range.start) + typed + $(this).val().substr(range.start);
if (dp == 0) {
if (!isInteger(text)) e.preventDefault();
}
else {
if (!isNumeric(text)) e.preventDefault();
}
return;
}
if (!e.charCode) k = String.fromCharCode(e.which);
else k = String.fromCharCode(e.charCode);
if (ch.indexOf(k) != -1) e.preventDefault();
if (e.ctrlKey && k == 'v') e.preventDefault();
}
);
$(this).bind('contextmenu', function() { return false });
}
);
};
$.fn.numeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
var opts = {};
if (!isNaN(p)) {
opts = $.extend({
nchars: az
}, { decimals: p });
} else {
opts = $.extend({
nchars: az
}, p);
}
return this.each(function() {
$(this).alphanumeric(opts);
}
);
};
$.fn.integer = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
p = {
nchars: az,
allow: '-',
decimals: 0
};
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
$.fn.alpha = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var nm = "1234567890";
p = $.extend({
nchars: nm
}, p);
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
})(jQuery);

Categories

Resources