jquery scannerDetection ignoreIfFocusOn:'input' not working - javascript

I am using scannerDetection.js to scan barcodes:
jQuery(document).ready(function () {
$(document).scannerDetection({ ignoreIfFocusOn: 'input[type="text"]' });
});
But the above setting does not work, as every time i focus an input element the barcode is displayed in the input box, plus form submit event is fired as well.
I tried using: $(document).scannerDetection({ preventDefault:true });
Which works, but unfortunately it also blocks my keyboard input.
I tried using different versions of jquery library with no success.
According to this article, plug-in and its settings should work just fine.
I tried looking at the source code for the plugin, but cannot quite figure it out:
(function ($) {
$.fn.scannerDetection = function (options) {
// If string given, call onComplete callback
if (typeof options === "string") {
this.each(function () {
this.scannerDetectionTest(options);
});
return this;
}
// If false (boolean) given, deinitialize plugin
if (options === false) {
this.each(function () {
this.scannerDetectionOff();
});
return this;
}
var defaults = {
onComplete: false, // Callback after detection of a successfull scanning (scanned string in parameter)
onError: false, // Callback after detection of a unsuccessfull scanning (scanned string in parameter)
onReceive: false, // Callback after receiving and processing a char (scanned char in parameter)
onKeyDetect: false, // Callback after detecting a keyDown (key char in parameter) - in contrast to onReceive, this fires for non-character keys like tab, arrows, etc. too!
timeBeforeScanTest: 100, // Wait duration (ms) after keypress event to check if scanning is finished
avgTimeByChar: 30, // Average time (ms) between 2 chars. Used to do difference between keyboard typing and scanning
minLength: 6, // Minimum length for a scanning
endChar: [9, 13], // Chars to remove and means end of scanning
startChar: [], // Chars to remove and means start of scanning
ignoreIfFocusOn: false, // do not handle scans if the currently focused element matches this selector
scanButtonKeyCode: false, // Key code of the scanner hardware button (if the scanner button a acts as a key itself)
scanButtonLongPressThreshold: 3, // How many times the hardware button should issue a pressed event before a barcode is read to detect a longpress
onScanButtonLongPressed: false, // Callback after detection of a successfull scan while the scan button was pressed and held down
stopPropagation: false, // Stop immediate propagation on keypress event
preventDefault: false // Prevent default action on keypress event
};
if (typeof options === "function") {
options = { onComplete: options }
}
if (typeof options !== "object") {
options = $.extend({}, defaults);
} else {
options = $.extend({}, defaults, options);
}
this.each(function () {
var self = this, $self = $(self), firstCharTime = 0, lastCharTime = 0, stringWriting = '', callIsScanner = false, testTimer = false, scanButtonCounter = 0;
var initScannerDetection = function () {
firstCharTime = 0;
stringWriting = '';
scanButtonCounter = 0;
};
self.scannerDetectionOff = function () {
$self.unbind('keydown.scannerDetection');
$self.unbind('keypress.scannerDetection');
}
self.isFocusOnIgnoredElement = function () {
if (!options.ignoreIfFocusOn) return false;
if (typeof options.ignoreIfFocusOn === 'string') return $(':focus').is(options.ignoreIfFocusOn);
if (typeof options.ignoreIfFocusOn === 'object' && options.ignoreIfFocusOn.length) {
var focused = $(':focus');
for (var i = 0; i < options.ignoreIfFocusOn.length; i++) {
if (focused.is(options.ignoreIfFocusOn[i])) {
return true;
}
}
}
return false;
}
self.scannerDetectionTest = function (s) {
// If string is given, test it
if (s) {
firstCharTime = lastCharTime = 0;
stringWriting = s;
}
if (!scanButtonCounter) {
scanButtonCounter = 1;
}
// If all condition are good (length, time...), call the callback and re-initialize the plugin for next scanning
// Else, just re-initialize
if (stringWriting.length >= options.minLength && lastCharTime - firstCharTime < stringWriting.length * options.avgTimeByChar) {
if (options.onScanButtonLongPressed && scanButtonCounter > options.scanButtonLongPressThreshold) options.onScanButtonLongPressed.call(self, stringWriting, scanButtonCounter);
else if (options.onComplete) options.onComplete.call(self, stringWriting, scanButtonCounter);
$self.trigger('scannerDetectionComplete', { string: stringWriting });
initScannerDetection();
return true;
} else {
if (options.onError) options.onError.call(self, stringWriting);
$self.trigger('scannerDetectionError', { string: stringWriting });
initScannerDetection();
return false;
}
}
$self.data('scannerDetection', { options: options }).unbind('.scannerDetection').bind('keydown.scannerDetection', function (e) {
// If it's just the button of the scanner, ignore it and wait for the real input
if (options.scanButtonKeyCode !== false && e.which == options.scanButtonKeyCode) {
scanButtonCounter++;
// Cancel default
e.preventDefault();
e.stopImmediatePropagation();
}
// Add event on keydown because keypress is not triggered for non character keys (tab, up, down...)
// So need that to check endChar and startChar (that is often tab or enter) and call keypress if necessary
else if ((firstCharTime && options.endChar.indexOf(e.which) !== -1)
|| (!firstCharTime && options.startChar.indexOf(e.which) !== -1)) {
// Clone event, set type and trigger it
var e2 = jQuery.Event('keypress', e);
e2.type = 'keypress.scannerDetection';
$self.triggerHandler(e2);
// Cancel default
e.preventDefault();
e.stopImmediatePropagation();
}
// Fire keyDetect event in any case!
if (options.onKeyDetect) options.onKeyDetect.call(self, e);
$self.trigger('scannerDetectionKeyDetect', { evt: e });
}).bind('keypress.scannerDetection', function (e) {
if (this.isFocusOnIgnoredElement()) return;
if (options.stopPropagation) e.stopImmediatePropagation();
if (options.preventDefault) e.preventDefault();
if (firstCharTime && options.endChar.indexOf(e.which) !== -1) {
e.preventDefault();
e.stopImmediatePropagation();
callIsScanner = true;
} else if (!firstCharTime && options.startChar.indexOf(e.which) !== -1) {
e.preventDefault();
e.stopImmediatePropagation();
callIsScanner = false;
} else {
if (typeof (e.which) != 'undefined') {
stringWriting += String.fromCharCode(e.which);
}
callIsScanner = false;
}
if (!firstCharTime) {
firstCharTime = Date.now();
}
lastCharTime = Date.now();
if (testTimer) clearTimeout(testTimer);
if (callIsScanner) {
self.scannerDetectionTest();
testTimer = false;
} else {
testTimer = setTimeout(self.scannerDetectionTest, options.timeBeforeScanTest);
}
if (options.onReceive) options.onReceive.call(self, e);
$self.trigger('scannerDetectionReceive', { evt: e });
});
});
return this;
}
})(jQuery);
Any suggestions?

The original source code contained this line of code:
.bind('keypress.scannerDetection',function(e){
if (this.isFocusOnIgnoredElement()) return;
As you can see, it returns nothing. Just add false after the return statement:
.bind('keypress.scannerDetection',function(e){
if (this.isFocusOnIgnoredElement()) return true;
That worked for me. Although there is another issue:
barcode appears on focused input field

Related

tag-it.js not incrementing counter on fieldname

I am trying to generate hidden inputs with tag-it.js (GitHub For Code Here) that has a dynamic field name. I have built PHP application that depends on the names having an index starting at 1 instead of 0 (use case specific reasons). Going through documentation, I am able to add a method to my instance of tagit() that triggers after a tag is added. I am using alerts to confirm that the count is increasing by one but for some reason, the field name is still only using the initial value of count.
PHP SNIPPET
<?php
$loop_count = 0;
$location_count = 1;
do {
?>
<p>Zip Codes</p>
<ul id="location_<?php echo $location_count; ?>_zips" data-locnum="<?php echo $location_count; ?>"></ul>
<?php
$loop_count++;
$location_count++;
} while ($loop_count < 3);
?>
JavaScript SNIPPET
jQuery(function () {
let count = 1;
$('*[data-locNum]').each(function () {
let $locNum = $(this).attr('data-locNum');
$(this).tagit({
fieldName: "franchise[location][" + $locNum + "][zip][" + count + "]",
removeConfirmation: true,
allowDuplicates: false,
allowSpaces: true,
placeholderText: 'Add a Zip',
afterTagAdded: function () {
top.alert(count);
count++;
top.alert(count);
}
});
});
});
The tagit js found at the link above is not working with the latest version of jquery. That is why have included my own version of the tag-it.js below, in case you wish to use it in testing this code out.
Custom tag-it.js FULL
/*
* jQuery UI Tag-it!
*
* #version v2.0 (06/2011)
*
* Copyright 2011, Levy Carneiro Jr.
* Released under the MIT license.
* http://aehlke.github.com/tag-it/LICENSE
*
* Homepage:
* http://aehlke.github.com/tag-it/
*
* Authors:
* Levy Carneiro Jr.
* Martin Rehfeld
* Tobias Schmidt
* Skylar Challand
* Alex Ehlke
*
* Maintainer:
* Alex Ehlke - Twitter: #aehlke
*
* Dependencies:
* jQuery v1.4+
* jQuery UI v1.8+
*/
(function($) {
$.widget('ui.tagit', {
options: {
allowDuplicates : false,
caseSensitive : true,
fieldName : 'tags',
placeholderText : null, // Sets `placeholder` attr on input field.
readOnly : false, // Disables editing.
removeConfirmation: false, // Require confirmation to remove tags.
tagLimit : null, // Max number of tags allowed (null for unlimited).
// Used for autocomplete, unless you override `autocomplete.source`.
availableTags : [],
// Use to override or add any options to the autocomplete widget.
//
// By default, autocomplete.source will map to availableTags,
// unless overridden.
autocomplete: {},
// Shows autocomplete before the user even types anything.
showAutocompleteOnFocus: false,
// When enabled, quotes are unneccesary for inputting multi-word tags.
allowSpaces: false,
// The below options are for using a single field instead of several
// for our form values.
//
// When enabled, will use a single hidden field for the form,
// rather than one per tag. It will delimit tags in the field
// with singleFieldDelimiter.
//
// The easiest way to use singleField is to just instantiate tag-it
// on an INPUT element, in which case singleField is automatically
// set to true, and singleFieldNode is set to that element. This
// way, you don't need to fiddle with these options.
singleField: false,
// This is just used when preloading data from the field, and for
// populating the field with delimited tags as the user adds them.
singleFieldDelimiter: ',',
// Set this to an input DOM node to use an existing form field.
// Any text in it will be erased on init. But it will be
// populated with the text of tags as they are created,
// delimited by singleFieldDelimiter.
//
// If this is not set, we create an input node for it,
// with the name given in settings.fieldName.
singleFieldNode: null,
// Whether to animate tag removals or not.
animate: true,
// Optionally set a tabindex attribute on the input that gets
// created for tag-it.
tabIndex: null,
// Event callbacks.
beforeTagAdded : null,
afterTagAdded : null,
beforeTagRemoved : null,
afterTagRemoved : null,
onTagClicked : null,
onTagLimitExceeded : null,
// DEPRECATED:
//
// /!\ These event callbacks are deprecated and WILL BE REMOVED at some
// point in the future. They're here for backwards-compatibility.
// Use the above before/after event callbacks instead.
onTagAdded : null,
onTagRemoved: null,
// `autocomplete.source` is the replacement for tagSource.
tagSource: null
// Do not use the above deprecated options.
},
_create: function() {
// for handling static scoping inside callbacks
let that = this;
// There are 2 kinds of DOM nodes this widget can be instantiated on:
// 1. UL, OL, or some element containing either of these.
// 2. INPUT, in which case 'singleField' is overridden to true,
// a UL is created and the INPUT is hidden.
if (this.element.is('input')) {
this.tagList = $('<ul></ul>').insertAfter(this.element);
this.options.singleField = true;
this.options.singleFieldNode = this.element;
this.element.addClass('tagit-hidden-field');
} else {
this.tagList = this.element.find('ul, ol').addBack().last();
}
this.tagInput = $('<input type="text" />').addClass('ui-widget-content');
if (this.options.readOnly) this.tagInput.attr('disabled', 'disabled');
if (this.options.tabIndex) {
this.tagInput.attr('tabindex', this.options.tabIndex);
}
if (this.options.placeholderText) {
this.tagInput.attr('placeholder', this.options.placeholderText);
}
if (!this.options.autocomplete.source) {
this.options.autocomplete.source = function(search, showChoices) {
let filter = search.term.toLowerCase();
let choices = $.grep(this.options.availableTags, function(element) {
// Only match autocomplete options that begin with the search term.
// (Case insensitive.)
return (element.toLowerCase().indexOf(filter) === 0);
});
if (!this.options.allowDuplicates) {
choices = this._subtractArray(choices, this.assignedTags());
}
showChoices(choices);
};
}
if (this.options.showAutocompleteOnFocus) {
this.tagInput.focus(function(event, ui) {
that._showAutocomplete();
});
if (typeof this.options.autocomplete.minLength === 'undefined') {
this.options.autocomplete.minLength = 0;
}
}
// Bind autocomplete.source callback functions to this context.
if ($.isFunction(this.options.autocomplete.source)) {
this.options.autocomplete.source = $.proxy(this.options.autocomplete.source, this);
}
// DEPRECATED.
if ($.isFunction(this.options.tagSource)) {
this.options.tagSource = $.proxy(this.options.tagSource, this);
}
this.tagList
.addClass('tagit')
.addClass('ui-widget ui-widget-content ui-corner-all')
// Create the input field.
.append($('<li class="tagit-new"></li>').append(this.tagInput))
.click(function(e) {
let target = $(e.target);
if (target.hasClass('tagit-label')) {
let tag = target.closest('.tagit-choice');
if (!tag.hasClass('removed')) {
that._trigger('onTagClicked', e, {tag: tag, tagLabel: that.tagLabel(tag)});
}
} else {
// Sets the focus() to the input field, if the user
// clicks anywhere inside the UL. This is needed
// because the input field needs to be of a small size.
that.tagInput.focus();
}
});
// Single field support.
let addedExistingFromSingleFieldNode = false;
if (this.options.singleField) {
if (this.options.singleFieldNode) {
// Add existing tags from the input field.
let node = $(this.options.singleFieldNode);
let tags = node.val().split(this.options.singleFieldDelimiter);
node.val('');
$.each(tags, function(index, tag) {
that.createTag(tag, null, true);
addedExistingFromSingleFieldNode = true;
});
} else {
// Create our single field input after our list.
this.options.singleFieldNode = $('<input type="hidden" style="display:none;" value="" name="' + this.options.fieldName + '" />');
this.tagList.after(this.options.singleFieldNode);
}
}
// Add existing tags from the list, if any.
if (!addedExistingFromSingleFieldNode) {
this.tagList.children('li').each(function() {
if (!$(this).hasClass('tagit-new')) {
that.createTag($(this).text(), $(this).attr('class'), true);
$(this).remove();
}
});
}
// Events.
this.tagInput
.keydown(function(event) {
// Backspace is not detected within a keypress, so it must use keydown.
if (event.which == $.ui.keyCode.BACKSPACE && that.tagInput.val() === '') {
let tag = that._lastTag();
if (!that.options.removeConfirmation || tag.hasClass('remove')) {
// When backspace is pressed, the last tag is deleted.
that.removeTag(tag);
} else if (that.options.removeConfirmation) {
tag.addClass('remove ui-state-highlight');
}
} else if (that.options.removeConfirmation) {
that._lastTag().removeClass('remove ui-state-highlight');
}
// Comma/Space/Enter are all valid delimiters for new tags,
// except when there is an open quote or if setting allowSpaces = true.
// Tab will also create a tag, unless the tag input is empty,
// in which case it isn't caught.
if (
(event.which === $.ui.keyCode.COMMA && event.shiftKey === false) ||
event.which === $.ui.keyCode.ENTER ||
(
event.which == $.ui.keyCode.TAB &&
that.tagInput.val() !== ''
) ||
(
event.which == $.ui.keyCode.SPACE &&
that.options.allowSpaces !== true &&
(
$.trim(that.tagInput.val()).replace( /^s*/, '' ).charAt(0) != '"' ||
(
$.trim(that.tagInput.val()).charAt(0) == '"' &&
$.trim(that.tagInput.val()).charAt($.trim(that.tagInput.val()).length - 1) == '"' &&
$.trim(that.tagInput.val()).length - 1 !== 0
)
)
)
) {
// Enter submits the form if there's no text in the input.
if (!(event.which === $.ui.keyCode.ENTER && that.tagInput.val() === '')) {
event.preventDefault();
}
// Autocomplete will create its own tag from a selection and close automatically.
if (!(that.options.autocomplete.autoFocus && that.tagInput.data('autocomplete-open'))) {
that.tagInput.autocomplete('close');
that.createTag(that._cleanedInput());
}
}
}).blur(function(e){
// Create a tag when the element loses focus.
// If autocomplete is enabled and suggestion was clicked, don't add it.
if (!that.tagInput.data('autocomplete-open')) {
that.createTag(that._cleanedInput());
}
});
// Autocomplete.
if (this.options.availableTags || this.options.tagSource || this.options.autocomplete.source) {
let autocompleteOptions = {
select: function(event, ui) {
that.createTag(ui.item.value);
// Preventing the tag input to be updated with the chosen value.
return false;
}
};
$.extend(autocompleteOptions, this.options.autocomplete);
// tagSource is deprecated, but takes precedence here since autocomplete.source is set by default,
// while tagSource is left null by default.
autocompleteOptions.source = this.options.tagSource || autocompleteOptions.source;
this.tagInput.autocomplete(autocompleteOptions).bind('autocompleteopen.tagit', function(event, ui) {
that.tagInput.data('autocomplete-open', true);
}).bind('autocompleteclose.tagit', function(event, ui) {
that.tagInput.data('autocomplete-open', false);
});
this.tagInput.autocomplete('widget').addClass('tagit-autocomplete');
}
},
destroy: function() {
$.Widget.prototype.destroy.call(this);
this.element.unbind('.tagit');
this.tagList.unbind('.tagit');
this.tagInput.removeData('autocomplete-open');
this.tagList.removeClass([
'tagit',
'ui-widget',
'ui-widget-content',
'ui-corner-all',
'tagit-hidden-field'
].join(' '));
if (this.element.is('input')) {
this.element.removeClass('tagit-hidden-field');
this.tagList.remove();
} else {
this.element.children('li').each(function() {
if ($(this).hasClass('tagit-new')) {
$(this).remove();
} else {
$(this).removeClass([
'tagit-choice',
'ui-widget-content',
'ui-state-default',
'ui-state-highlight',
'ui-corner-all',
'remove',
'tagit-choice-editable',
'tagit-choice-read-only'
].join(' '));
$(this).text($(this).children('.tagit-label').text());
}
});
if (this.singleFieldNode) {
this.singleFieldNode.remove();
}
}
return this;
},
_cleanedInput: function() {
// Returns the contents of the tag input, cleaned and ready to be passed to createTag
return $.trim(this.tagInput.val().replace(/^"(.*)"$/, '$1'));
},
_lastTag: function() {
return this.tagList.find('.tagit-choice:last:not(.removed)');
},
_tags: function() {
return this.tagList.find('.tagit-choice:not(.removed)');
},
assignedTags: function() {
// Returns an array of tag string values
let that = this;
let tags = [];
if (this.options.singleField) {
tags = $(this.options.singleFieldNode).val().split(this.options.singleFieldDelimiter);
if (tags[0] === '') {
tags = [];
}
} else {
this._tags().each(function() {
tags.push(that.tagLabel(this));
});
}
return tags;
},
_updateSingleTagsField: function(tags) {
// Takes a list of tag string values, updates this.options.singleFieldNode.val to the tags delimited by this.options.singleFieldDelimiter
$(this.options.singleFieldNode).val(tags.join(this.options.singleFieldDelimiter)).trigger('change');
},
_subtractArray: function(a1, a2) {
let result = [];
for (let i = 0; i < a1.length; i++) {
if ($.inArray(a1[i], a2) == -1) {
result.push(a1[i]);
}
}
return result;
},
tagLabel: function(tag) {
// Returns the tag's string label.
if (this.options.singleField) {
return $(tag).find('.tagit-label:first').text();
} else {
return $(tag).find('input:first').val();
}
},
_showAutocomplete: function() {
this.tagInput.autocomplete('search', '');
},
_findTagByLabel: function(name) {
let that = this;
let tag = null;
this._tags().each(function(i) {
if (that._formatStr(name) == that._formatStr(that.tagLabel(this))) {
tag = $(this);
return false;
}
});
return tag;
},
_isNew: function(name) {
return !this._findTagByLabel(name);
},
_formatStr: function(str) {
if (this.options.caseSensitive) {
return str;
}
return $.trim(str.toLowerCase());
},
_effectExists: function(name) {
return Boolean($.effects && ($.effects[name] || ($.effects.effect && $.effects.effect[name])));
},
createTag: function(value, additionalClass, duringInitialization) {
let that = this;
value = $.trim(value);
if(this.options.preprocessTag) {
value = this.options.preprocessTag(value);
}
if (value === '') {
return false;
}
if (!this.options.allowDuplicates && !this._isNew(value)) {
let existingTag = this._findTagByLabel(value);
if (this._trigger('onTagExists', null, {
existingTag: existingTag,
duringInitialization: duringInitialization
}) !== false) {
if (this._effectExists('highlight')) {
existingTag.effect('highlight');
}
}
return false;
}
if (this.options.tagLimit && this._tags().length >= this.options.tagLimit) {
this._trigger('onTagLimitExceeded', null, {duringInitialization: duringInitialization});
return false;
}
let label = $(this.options.onTagClicked ? '<a class="tagit-label"></a>' : '<span class="tagit-label"></span>').text(value);
// Create tag.
let tag = $('<li></li>')
.addClass('tagit-choice ui-widget-content ui-state-default ui-corner-all')
.addClass(additionalClass)
.append(label);
if (this.options.readOnly){
tag.addClass('tagit-choice-read-only');
} else {
tag.addClass('tagit-choice-editable');
// Button for removing the tag.
let removeTagIcon = $('<span></span>')
.addClass('ui-icon ui-icon-close');
let removeTag = $('<a><span class="text-icon">\xd7</span></a>') // \xd7 is an X
.addClass('tagit-close')
.append(removeTagIcon)
.click(function(e) {
// Removes a tag when the little 'x' is clicked.
that.removeTag(tag);
});
tag.append(removeTag);
}
// Unless options.singleField is set, each tag has a hidden input field inline.
if (!this.options.singleField) {
let escapedValue = label.html();
tag.append('<input type="hidden" value="' + escapedValue + '" name="' + this.options.fieldName + '" class="tagit-hidden-field" />');
}
if (this._trigger('beforeTagAdded', null, {
tag: tag,
tagLabel: this.tagLabel(tag),
duringInitialization: duringInitialization
}) === false) {
return;
}
if (this.options.singleField) {
let tags = this.assignedTags();
tags.push(value);
this._updateSingleTagsField(tags);
}
// DEPRECATED.
this._trigger('onTagAdded', null, tag);
this.tagInput.val('');
// Insert tag.
this.tagInput.parent().before(tag);
this._trigger('afterTagAdded', null, {
tag: tag,
tagLabel: this.tagLabel(tag),
duringInitialization: duringInitialization
});
if (this.options.showAutocompleteOnFocus && !duringInitialization) {
setTimeout(function () { that._showAutocomplete(); }, 0);
}
},
removeTag: function(tag, animate) {
animate = typeof animate === 'undefined' ? this.options.animate : animate;
tag = $(tag);
// DEPRECATED.
this._trigger('onTagRemoved', null, tag);
if (this._trigger('beforeTagRemoved', null, {tag: tag, tagLabel: this.tagLabel(tag)}) === false) {
return;
}
if (this.options.singleField) {
let tags = this.assignedTags();
let removedTagLabel = this.tagLabel(tag);
tags = $.grep(tags, function(el){
return el != removedTagLabel;
});
this._updateSingleTagsField(tags);
}
if (animate) {
tag.addClass('removed'); // Excludes this tag from _tags.
let hide_args = this._effectExists('blind') ? ['blind', {direction: 'horizontal'}, 'fast'] : ['fast'];
let thisTag = this;
hide_args.push(function() {
tag.remove();
thisTag._trigger('afterTagRemoved', null, {tag: tag, tagLabel: thisTag.tagLabel(tag)});
});
tag.fadeOut('fast').hide.apply(tag, hide_args).dequeue();
} else {
tag.remove();
this._trigger('afterTagRemoved', null, {tag: tag, tagLabel: this.tagLabel(tag)});
}
},
removeTagByLabel: function(tagLabel, animate) {
let toRemove = this._findTagByLabel(tagLabel);
if (!toRemove) {
throw "No such tag exists with the name '" + tagLabel + "'";
}
this.removeTag(toRemove, animate);
},
removeAll: function() {
// Removes all tags.
let that = this;
this._tags().each(function(index, tag) {
that.removeTag(tag, false);
});
}
});
})(jQuery);
This isn't a perfect solution but I found a good way to force the name attribute to rely on variables that are in the javascript.
jQuery(function () {
let tagArrays = [];
let count = 1;
$('*[data-locNum]')
.each(function () {
let locNum = $(this).attr('data-locNum');
$(this).tagit({
fieldName: "franchise[location][" + locNum + "][zip][" + count + "]",
removeConfirmation: true,
allowDuplicates: false,
allowSpaces: true,
placeholderText: 'Add a Zip',
// This changed to go with the attributes that the tag-it.js automatically passes to this
// method.
afterTagAdded: function (event, ui) {
let tagged = ui.tag;
tagged.find('input').attr("name", "franchise[location][" + locNum + "][zip][" + count + "]");
count++;
}
});
});
});

Javascript key listener press any key

I have a problem and I need to find a solution. :D
So here's my code:
var inputEnabled = true
var pressedKey = {}
window.addEventListener('keydown',function(e) {
pressedKey[e.keyCode || e.which] = true;
}, true);
window.addEventListener('keyup',function(e) {
pressedKey[e.keyCode || e.which] = false;
}, true);
function keyBinding() {
if (*my problem*) {
loadMenu()
}
if (inputEnabled == true) {
setTimeout("keyBinding()", 25)
}
}
What I want is that when any key is pressed I want to load a menu but I don't what how am I supposed to detect that key press.
Any help would be appreciated.
try this where *my problem* is in your code:
if(Objects.keys(pressedKey).length>0){ // checks if the object 'pressedKey' contains atleast one key
loadMenu()
}
However I recommend checking for the key press directly inside the key listener:
var inputEnabled = true
var menuLoaded = false; // this will indicate if the menu is loaded already
var pressedKey = {}
window.addEventListener('keydown', function (e) {
if(!menuLoaded){ // check if menu is not open
loadMenu()
menuLoaded = true
}
pressedKey[e.keyCode || e.which] = true;
}, true);
window.addEventListener('keyup', function (e) {
pressedKey[e.keyCode || e.which] = false;
}, true);

How do I call a sub-function from within a function object in javascript

I've checked the related questions on stack overflow, but can't seem to find an answer to my predicament. I'm trying to use a plugin for javascript (Tag it! - Tag Editor) and I need to find a way to call one of its functions "create_choice()" EDIT: at some point after it has been initiated. Is there a way after calling :
$tagit = $("#mytags").tagit();
that I can then call something like
$tagit.create_choice('test123');
Here is a link for the example :
http://levycarneiro.com/projects/tag-it/example.html
Below is the code from the plugin if it is any help
(function($) {
$.fn.tagit = function(options) {
var el = this;
const BACKSPACE = 8;
const ENTER = 13;
const SPACE = 32;
const COMMA = 44;
// add the tagit CSS class.
el.addClass("tagit");
// create the input field.
var html_input_field = "<li class=\"tagit-new\"><input class=\"tagit-input\" type=\"text\" /></li>\n";
el.html (html_input_field);
tag_input = el.children(".tagit-new").children(".tagit-input");
$(this).click(function(e){
if (e.target.tagName == 'A') {
// Removes a tag when the little 'x' is clicked.
// Event is binded to the UL, otherwise a new tag (LI > A) wouldn't have this event attached to it.
$(e.target).parent().remove();
}
else {
// Sets the focus() to the input field, if the user clicks anywhere inside the UL.
// This is needed because the input field needs to be of a small size.
tag_input.focus();
}
});
tag_input.keypress(function(event){
if (event.which == BACKSPACE) {
if (tag_input.val() == "") {
// When backspace is pressed, the last tag is deleted.
$(el).children(".tagit-choice:last").remove();
}
}
// Comma/Space/Enter are all valid delimiters for new tags.
else if (event.which == COMMA || event.which == SPACE || event.which == ENTER) {
event.preventDefault();
var typed = tag_input.val();
typed = typed.replace(/,+$/,"");
typed = typed.trim();
if (typed != "") {
if (is_new (typed)) {
create_choice (typed);
}
// Cleaning the input.
tag_input.val("");
}
}
});
tag_input.autocomplete({
source: options.availableTags,
select: function(event,ui){
if (is_new (ui.item.value)) {
create_choice (ui.item.value);
}
// Cleaning the input.
tag_input.val("");
// Preventing the tag input to be update with the chosen value.
return false;
}
});
function is_new (value){
var is_new = true;
this.tag_input.parents("ul").children(".tagit-choice").each(function(i){
n = $(this).children("input").val();
if (value == n) {
is_new = false;
}
})
return is_new;
}
function create_choice (value){
var el = "";
el = "<li class=\"tagit-choice\">\n";
el += value + "\n";
el += "<a class=\"close\">x</a>\n";
el += "<input type=\"hidden\" style=\"display:none;\" value=\""+value+"\" name=\"item[tags][]\">\n";
el += "</li>\n";
var li_search_tags = this.tag_input.parent();
$(el).insertBefore (li_search_tags);
this.tag_input.val("");
}
};
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
})(jQuery);
I've created a working example at http://jsfiddle.net/nickywaites/DnkBt/ but it does require making changes to the plugin.
Change
$.fn.tagit = function(options) { ...
to
$.fn.tagit = function(options,callback) { ...
Add
if (callback && typeof callback == 'function') {
callback();
}
after
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
Now you can call a function of your choice right after the tagit call:
$tagit = $("#mytags").tagit(yourOptions, function(){
alert('hi')!
});
You can try to add
return this;
right after the function create_choice block. tagit will return itself and you can call make_choice or any function contained in .fn.tagit

How to detect if the event is a browser event or not

How would you test if an event is a browser event (e.g. click, load, blur etc) based on its name (e.g. click)? (and no I'm not using jQuery/mootools/prototype/dojo)
UPDATE:
In this function I attach browser events (click and load) for example:
observe: function(elements, eventName, callback) {
if (!(elements.length != null)) {
elements = [elements];
}
return this.each(elements, function(e) {
if (helper.hooks.eventObserved != null) {
helper.hooks.eventObserved(eventName, callback, e);
}
if (typeof e === 'string') {
e = this.el(e);
}
if (e.addEventListener) {
return e.addEventListener(eventName, callback, false);
} else if (e.attachEvent) {
return e.attachEvent("on" + eventName, callback);
}
});
},
And this fires the event:
fire: function(elements, eventName) {
if (!(elements.length != null)) {
elements = [elements];
}
return this.each(elements, function(e) {
var evt;
if (document.createEventObject != null) {
evt = document.createEventObject();
return e.fireEvent("on" + eventName);
} else {
evt = document.createEvent('HTMLEvents');
evt.initEvent(eventName, true, true);
return !e.dispatchEvent(evt);
}
});
},
But what I want is to test if the event exists for example click is a browser event but login isn't so how would I test that?
Check out this solution by Juriy Zaytsev (live demo).
jQuery itself uses it.
You could check to see if the function/object element["on"+event] exists:
test
<script>
function doesElementHaveEvent(element, event){
return (typeof element["on"+event] != typeof undefined);
}
alert(doesElementHaveEvent(document.getElementById("myAnchor"), "click")); // true
alert(doesElementHaveEvent(document.getElementById("myAnchor"), "login")); // false
</script>

Cycle Focus to First Form Element from Last Element & Vice Versa

I have created a form with malsup's Form Plugin wherein it submits on change of the inputs. I have set up my jQuery script to index drop down menus and visible inputs, and uses that index to determine whether keydown of tab should move focus to the next element or the first element, and likewise with shift+tab keydown. However, instead of moving focus to the first element from the last element on tab keydown like I would like it to, it moves focus to the second element. How can I change it to cycle focus to the actual first and last elements? Here is a live link to my form: http://www.presspound.org/calculator/ajax/sample.php. Thanks to anyone that tries to help. Here is my script:
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
var shiftDown = false;
$('input, select').each(function (i) {
$(this).data('initial', $(this).val());
});
$('input, select').keyup(function(event) {
if (event.keyCode==16) {
shiftDown = false;
$('#shiftCatch').val(shiftDown);
}
});
$('input, select').keydown(function(event) {
if (event.keyCode==16) {
shiftDown = true;
$('#shiftCatch').val(shiftDown);
}
if (event.keyCode==13) {
$('#captured').val(event.target.id);
} else if (event.keyCode==9 && shiftDown==false) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var nextEl = fields.eq(index+1).attr('id');
var firstEl = fields.eq(0).attr('id');
var focusEl = '#'+firstEl;
if (index>-1 && (index+1)<fields.length) {
$('#captured').val(nextEl);
} else if(index+1>=fields.length) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(firstEl);
} else {
event.preventDefault();
$(focusEl).focus();
}
}
return false;
});
} else if (event.keyCode==9 && shiftDown==true) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var prevEl = fields.eq(index-1).attr('id');
var lastEl = fields.eq(fields.length-1).attr('id');
var focusEl = '#'+lastEl;
if (index<fields.length && (index-1)>-1) {
$('#captured').val(prevEl);
} else if (index==0) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(lastEl);
} else {
event.preventDefault();
$(focusEl).select();
}
}
return false;
});
}
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 100 );
}
}
Edit #1: I made a few minor changes to the code, which has brought me a little closer to my intended functionality of the script. However, I only made one change to the code pertaining to the focus: I tried to to disable the tab keydown when pressed on the last element (and also the shift+tab keydown on the first element) in an attempt to force the focus on the element I want without skipping over it like it has been doing. This is the code I added:
$(this).one('keydown', function (event) {
return !(event.keyCode==9 && shiftDown==true);
});
This kind of works. After the page loads, If the user presses tab on the last element without making a change to its value, the focus will be set to the second element. However, the second time the user presses tab on the last element without making a change to its value, and every subsequent time thereafter, the focus will be set to the first element, just as I would like it to.
Edit #2: I replaced the code in Edit #1, with code utilizing event.preventDefault(), which works better. While if a user does a shift+tab keydown when in the first element, the focus moves to the last element as it should. However, if the user continues to hold down the shift key and presses tab again, focus will be set back to the first element. And if the user continues to hold the shift key down still yet and hits tab, the focus will move back to the last element. The focus will shift back and forth between the first and last element until the user lifts the shift key. This problem does not occur when only pressing tab. Here is the new code snippet:
event.preventDefault();
$(focusEl).focus();
You have a lot of code I didn't get full overview over, so I don't know if I missed some functionality you wanted integrated, but for the tabbing/shift-tabbing through form elements, this should do the work:
var elements = $("#container :input:visible");
var n = elements.length;
elements
.keydown(function(event){
if (event.keyCode == 9) { //if tab
var currentIndex = elements.index(this);
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
if (el.attr("type") == "text")
elements.eq(newIndex).select();
else
elements.eq(newIndex).focus();
event.preventDefault();
}
});
elements will be the jQuery object containing all the input fields, in my example it's all the input fields inside the div #container
Here's a demo: http://jsfiddle.net/rA3L9/
Here is the solution, which I couldn't have reached it without Simen's help. Thanks again, Simen.
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
$('#calculator :input:visible').each(function (i) {
$(this).data('initial', $(this).val());
});
return $(event.target).each(function() {
$('#c_main :input:visible').live(($.browser.opera ? 'keypress' : 'keydown'), function(event){
var elements = $("#calculator :input:visible");
var n = elements.length;
var currentIndex = elements.index(this);
if (event.keyCode == 13) { //if enter
var focusElement = elements.eq(currentIndex).attr('id');
$('#captured').val(focusElement);
} else if (event.keyCode == 9) { //if tab
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
var focusElement = el.attr('id');
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(focusElement);
} else if ((currentIndex==0 && event.shiftKey) || (currentIndex==n-1 && !event.shiftKey)) {
event.preventDefault();
if (el.attr('type')=='text') {
$.browser.msie ? "" : $(window).scrollTop(5000);
el.select().delay(800);
} else {
$.browser.msie ? "" : $(window).scrollTop(-5000);
el.focus().delay(800);
}
} else if (el.is('select')) {
event.preventDefault();
if (el.attr('type')=='text') {
el.select();
} else {
el.focus();
}
}
}
});
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 1 );
}
}
I put my files available to download in my live link: http://www.presspound.org/calculator/ajax/sample.php

Categories

Resources