I am a newbie in using tag-it. Below I am pasting the code. Earlier the autocomplete feature wasn't working but it is for now. The reason is it doesn't show all words which I've added in the array.
new.html
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
<link href="css/jquery.tagit.css" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/tag-it.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#myTags").tagit();
});
</script>
</head>
<body>
<ul id="myTags">
<!-- Existing list items will be pre-added to the tags -->
<li>Tag1</li>
<li>Tag2</li>
</ul>
</body>
</html>
tag-it.js
/*
* 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: {
fieldName : 'tags',
// Used for autocomplete, unless you override `autocomplete.source`.
availableTags : ['php','c++','perl','asp.net','bootstrap','dreamweaver'],
allowDuplicates : false,
caseSensitive : true,
placeholderText : null, // Sets `placeholder` attr on input field.
readOnly : false, // Disables editing.
removeConfirmation: false, // Require confirmation to remove tags.
// 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,
// 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
var 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.css('display', 'none');
} else {
this.tagList = this.element.find('ul, ol').andSelf().last();
}
this.tagInput = $('<input type="text" autocomplete="on"/>').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) {
var filter = search.term.toLowerCase();
var 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);
});
showChoices(this._subtractArray(choices, this.assignedTags()));
};
}
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) {
var target = $(e.target);
if (target.hasClass('tagit-label')) {
var tag = target.closest('.tagit-choice');
if (!tag.hasClass('removed')) {
that._trigger('onTagClicked', e, {tag: tag, tagLabel: this.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.
var addedExistingFromSingleFieldNode = false;
if (this.options.singleField) {
if (this.options.singleFieldNode) {
// Add existing tags from the input field.
var node = $(this.options.singleFieldNode);
var 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() === '') {
var 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.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();
}
that.createTag(that._cleanedInput());
// The autocomplete doesn't close automatically when TAB is pressed.
// So let's ensure that it closes.
that.tagInput.autocomplete('close');
}
}).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) {
var 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', function(event, ui) {
that.tagInput.data('autocomplete-open', true);
}).bind('autocompleteclose', function(event, ui) {
that.tagInput.data('autocomplete-open', false)
});
}
},
_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
var that = this;
var 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) {
var result = [];
for (var 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) {
var that = this;
var 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) {
var that = this;
value = $.trim(value);
if (value === '') {
return false;
}
if (!this.allowDuplicates && !this._isNew(value)) {
var existingTag = this._findTagByLabel(value);
if (this._trigger('onTagExists', null, {
existingTag: existingTag,
duringInitialization: duringInitialization
}) !== false) {
if (this._effectExists('highlight')) {
existingTag.effect('highlight');
}
}
return false;
}
var label = $(this.options.onTagClicked ? '<a class="tagit-label"></a>' : '<span class="tagit-label"></span>').text(value);
// Create tag.
var 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.
var removeTagIcon = $('<span></span>')
.addClass('ui-icon ui-icon-close');
var 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) {
var escapedValue = label.html();
tag.append('<input type="hidden" style="display:none;" value="' + escapedValue + '" name="' + this.options.fieldName + '" />');
}
if (this._trigger('beforeTagAdded', null, {
tag: tag,
tagLabel: this.tagLabel(tag),
duringInitialization: duringInitialization
}) === false) {
return;
}
if (this.options.singleField) {
var 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) {
var tags = this.assignedTags();
var 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.
var hide_args = this._effectExists('blind') ? ['blind', {direction: 'horizontal'}, 'fast'] : ['fast'];
hide_args.push(function() {
tag.remove();
});
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) {
var toRemove = this._findTagByLabel(tagLabel);
if (!toRemove) {
throw "No such tag exists with the name '" + tagLabel + "'";
}
this.removeTag(toRemove, animate);
},
removeAll: function() {
// Removes all tags.
var that = this;
this._tags().each(function(index, tag) {
that.removeTag(tag, false);
});
}
});
})(jQuery);
I have included tagit.min.js, jquery.tagit.css and tagit.ui-zendesk.css too.
<ul id="myTags" ></ul>
$(function(){
$("#myTags").tagit();
});
change
// Used for autocomplete, unless you override `autocomplete.source`.
availableTags : ['php','c++','perl','asp.net','bootstrap','dreamweaver'],
to this
var sampleTags = [
c++', 'java', 'php', 'coldfusion', 'javascript', 'asp', 'ruby', 'python', 'c', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'
],
or try to use the latest tagit
Related
I've implemented the select2 plugin with some customization to hide selected tags (I build them in a separated box), custom search (words between ( and ) shouldn't be in search scope) and avoid close dropdown when an element is selected or unselected.
The last features I would like to implement is that when an user use arrow keys to navigate inside dropdown and press enter on an element already selected, I would like to deselect it, and leave dropdown open.
I tried by listening all events fired by select2 but I can't deselect and prevent dropdown closing when user select the element by hit enter button on an already selected item.
But with mouse all is working fine!
var availableData = [{
"id": 38,
"text": "Test [38] (coding)"
},
{
"id": 62,
"text": "banana [62] (fruit)"
},
{
"id": 63,
"text": "apple [63] (fruit)"
},
{
"id": 65,
"text": "dog [65] (animal)"
},
];
// Init select 2
$('.js-example-basic-multiple').select2({
// Set multiple element select
multiple: true,
// Set a placeholder
placeholder: 'Select',
// It's better to set a static width, otherwise use bootstrap grids
// on container parent and set 100% width
width: '300px',
// Init plugin with data
data: availableData,
closeOnSelect: false,
templateSelection: function(ev, elem) {
// Hide selected elements
elem.hide();
},
matcher: function(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') return data;
// Do not display the item if there is no 'text' property
if (typeof data.text === 'undefined') return null;
// Regex that exclude all what is inside ()
const regex = /^(.+)\s\[([0-9]+)\]\s\((.+)\)$/gm;
// Apply regex
var matches = data.text.matchAll(regex).next();
// If no matches, return null
if (!matches) return null;
// If no groups was found, return null
if (!matches.value || matches.value.length === 0) return null;
// If on the first group was match, return it! (name)
if (matches.value[1].toLowerCase().indexOf(
params.term.toLowerCase()
) > -1) return data;
// If on the second group was match, return it! (id)
if (matches.value[2].toLowerCase().indexOf(
params.term.toLowerCase()
) > -1) return data;
// Return `null` if the term should not be displayed
return null;
}
});
$('.js-example-basic-multiple').on('select2:select', function(e) {
console.log("=> It's me, select2:select");
});
$('.js-example-basic-multiple').on('select2:closing', function(e) {
console.log("=> It's me, select2:closing", e);
});
$('.js-example-basic-multiple').on('select2:close', function(e) {
console.log("=> It's me, select2:close", e);
});
$('.js-example-basic-multiple').on('select2:opening', function(e) {
console.log("=> It's me, select2:opening");
});
$('.js-example-basic-multiple').on('select2:open', function(e) {
console.log("=> It's me, select2:open");
});
$('.js-example-basic-multiple').on('select2:selecting', function(e) {
console.log("=> It's me, select2:selecting");
});
$('.js-example-basic-multiple').on('select2:unselecting', function(e) {
console.log("=> It's me, select2:unselecting");
});
$('.js-example-basic-multiple').on('select2:unselect', function(e) {
console.log("=> It's me, select2:unselect");
});
$('.js-example-basic-multiple').on('select2:clearing', function(e) {
console.log("=> It's me, select2:clearing");
});
$('.js-example-basic-multiple').on('select2:clear', function(e) {
console.log("=> It's me, select2:clear");
});
// Select2 event: triggered whenever an option is selected or removed.
$('.js-example-basic-multiple').on('change', function(e) {
// If almost 1 id was selected, join with ',', otherwise blank string
var ids = $(this).val() ? $(this).val().join(',') : "";
console.log("TODO: Create elements with ids: ", ids);
// Append to the paragraph
$(".the-paragraph").empty().append("Your ids: " + ids);
});
<p>This is my HTML5 Boilerplate.</p>
<p>
<div>
<select class="js-example-basic-multiple"></select>
</div>
<p class="the-paragraph"></p>
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
Which characters are considered unsafe to allow for users to type in a text input field, to prevent hackers etc to perform SQL injections etc? Which characters should be blocked from the input?
For the record, I'm currently blocking the input with AngularJS using the following HTML:
<input type="text" ng-pattern-restrict='^[^<>#*"]+$'>
And here's the beautiful directive I found:
/* RESTRICT CERTAIN CHARACTERS IN INPUT FIELDS
<input type="text" ng-pattern-restrict="^[A-Za-z0-9]*$">
Alpha numeric chars only ^[A-Za-z0-9]*$
Date format YYYY-MM-DD ^\d{0,4}(-\d{0,2}(-\d{0,2})?)?$
*/
/*jslint browser: true, plusplus: true, indent: 2 */
// This will be removed by uglify, along with the DEBUG code
if (typeof DEBUG === 'undefined') {
DEBUG = true;
}
// Logic and fallbacks based on the following SO answers:
// - Getting caret position cross browser: http://stackoverflow.com/a/9370239/147507
// - Selection API on non input-text fields: http://stackoverflow.com/a/24247942/147507
// - Set cursor position on input text: http://stackoverflow.com/q/5755826/147507
angular.module('ngPatternRestrict', [])
.directive('ngPatternRestrict', ['$log', function ($log) {
'use strict';
function showDebugInfo() {
$log.debug("[ngPatternRestrict] " + Array.prototype.join.call(arguments, ' '));
}
return {
restrict: 'A',
require: "?ngModel",
compile: function uiPatternRestrictCompile() {
DEBUG && showDebugInfo("Loaded");
return function ngPatternRestrictLinking(scope, iElement, iAttrs, ngModelController) {
var regex, // validation regex object
oldValue, // keeping track of the previous value of the element
caretPosition, // keeping track of where the caret is at to avoid jumpiness
// housekeeping
initialized = false, // have we initialized our directive yet?
eventsBound = false, // have we bound our events yet?
// functions
getCaretPosition, // function to get the caret position, set in detectGetCaretPositionMethods
setCaretPosition; // function to set the caret position, set in detectSetCaretPositionMethods
//-------------------------------------------------------------------
// caret position
function getCaretPositionWithInputSelectionStart() {
return iElement[0].selectionStart; // we need to go under jqlite
}
function getCaretPositionWithDocumentSelection() {
// create a selection range from where we are to the beggining
// and measure how much we moved
var range = document.selection.createRange();
range.moveStart('character', -iElement.val().length);
return range.text.length;
}
function getCaretPositionWithWindowSelection() {
var s = window.getSelection(),
originalSelectionLength = String(s).length,
selectionLength,
didReachZero = false,
detectedCaretPosition,
restorePositionCounter;
do {
selectionLength = String(s).length;
s.modify('extend', 'backward', 'character');
// we're undoing a selection, and starting a new one towards the beggining of the string
if (String(s).length === 0) {
didReachZero = true;
}
} while (selectionLength !== String(s).length);
detectedCaretPosition = didReachZero ? selectionLength : selectionLength - originalSelectionLength;
s.collapseToStart();
restorePositionCounter = detectedCaretPosition;
while (restorePositionCounter-- > 0) {
s.modify('move', 'forward', 'character');
}
while (originalSelectionLength-- > 0) {
s.modify('extend', 'forward', 'character');
}
return detectedCaretPosition;
}
function setCaretPositionWithSetSelectionRange(position) {
iElement[0].setSelectionRange(position, position);
}
function setCaretPositionWithCreateTextRange(position) {
var textRange = iElement[0].createTextRange();
textRange.collapse(true);
textRange.moveEnd('character', position);
textRange.moveStart('character', position);
textRange.select();
}
function setCaretPositionWithWindowSelection(position) {
var s = window.getSelection(),
selectionLength;
do {
selectionLength = String(s).length;
s.modify('extend', 'backward', 'line');
} while (selectionLength !== String(s).length);
s.collapseToStart();
while (position--) {
s.modify('move', 'forward', 'character');
}
}
// HACK: Opera 12 won't give us a wrong validity status although the input is invalid
// we can select the whole text and check the selection size
// Congratulations to IE 11 for doing the same but not returning the selection.
function getValueLengthThroughSelection(input) {
// only do this on opera, since it'll mess up the caret position
// and break Firefox functionality
if (!/Opera/i.test(navigator.userAgent)) {
return 0;
}
input.focus();
document.execCommand("selectAll");
var focusNode = window.getSelection().focusNode;
return (focusNode || {}).selectionStart || 0;
}
//-------------------------------------------------------------------
// event handlers
function revertToPreviousValue() {
if (ngModelController) {
scope.$apply(function () {
ngModelController.$setViewValue(oldValue);
});
}
iElement.val(oldValue);
if (!angular.isUndefined(caretPosition)) {
setCaretPosition(caretPosition);
}
}
function updateCurrentValue(newValue) {
oldValue = newValue;
caretPosition = getCaretPosition();
}
function genericEventHandler(evt) {
DEBUG && showDebugInfo("Reacting to event:", evt.type);
//HACK Chrome returns an empty string as value if user inputs a non-numeric string into a number type input
// and this may happen with other non-text inputs soon enough. As such, if getting the string only gives us an
// empty string, we don't have the chance of validating it against a regex. All we can do is assume it's wrong,
// since the browser is rejecting it either way.
var newValue = iElement.val(),
inputValidity = iElement.prop("validity");
if (newValue === "" && iElement.attr("type") !== "text" && inputValidity && inputValidity.badInput) {
DEBUG && showDebugInfo("Value cannot be verified. Should be invalid. Reverting back to:", oldValue);
evt.preventDefault();
revertToPreviousValue();
} else if (newValue === "" && getValueLengthThroughSelection(iElement[0]) !== 0) {
DEBUG && showDebugInfo("Invalid input. Reverting back to:", oldValue);
evt.preventDefault();
revertToPreviousValue();
} else if (regex.test(newValue)) {
DEBUG && showDebugInfo("New value passed validation against", regex, newValue);
updateCurrentValue(newValue);
} else {
DEBUG && showDebugInfo("New value did NOT pass validation against", regex, newValue, "Reverting back to:", oldValue);
evt.preventDefault();
revertToPreviousValue();
}
}
//-------------------------------------------------------------------
// setup based on attributes
function tryParseRegex(regexString) {
try {
regex = new RegExp(regexString);
} catch (e) {
throw "Invalid RegEx string parsed for ngPatternRestrict: " + regexString;
}
}
//-------------------------------------------------------------------
// setup events
function bindListeners() {
if (eventsBound) {
return;
}
iElement.bind('input keyup click', genericEventHandler);
DEBUG && showDebugInfo("Bound events: input, keyup, click");
}
function unbindListeners() {
if (!eventsBound) {
return;
}
iElement.unbind('input', genericEventHandler);
//input: HTML5 spec, changes in content
iElement.unbind('keyup', genericEventHandler);
//keyup: DOM L3 spec, key released (possibly changing content)
iElement.unbind('click', genericEventHandler);
//click: DOM L3 spec, mouse clicked and released (possibly changing content)
DEBUG && showDebugInfo("Unbound events: input, keyup, click");
eventsBound = false;
}
//-------------------------------------------------------------------
// initialization
function readPattern() {
var entryRegex = !!iAttrs.ngPatternRestrict ? iAttrs.ngPatternRestrict : iAttrs.pattern;
DEBUG && showDebugInfo("RegEx to use:", entryRegex);
tryParseRegex(entryRegex);
}
function notThrows(testFn, shouldReturnTruthy) {
try {
return testFn() || !shouldReturnTruthy;
} catch (e) {
return false;
}
}
function detectGetCaretPositionMethods() {
var input = iElement[0];
// Chrome will throw on input.selectionStart of input type=number
// See http://stackoverflow.com/a/21959157/147507
if (notThrows(function () { return input.selectionStart; })) {
getCaretPosition = getCaretPositionWithInputSelectionStart;
} else {
// IE 9- will use document.selection
// TODO support IE 11+ with document.getSelection()
if (notThrows(function () { return document.selection; }, true)) {
getCaretPosition = getCaretPositionWithDocumentSelection;
} else {
getCaretPosition = getCaretPositionWithWindowSelection;
}
}
}
function detectSetCaretPositionMethods() {
var input = iElement[0];
if (typeof input.setSelectionRange === 'function') {
setCaretPosition = setCaretPositionWithSetSelectionRange;
} else if (typeof input.createTextRange === 'function') {
setCaretPosition = setCaretPositionWithCreateTextRange;
} else {
setCaretPosition = setCaretPositionWithWindowSelection;
}
}
function initialize() {
if (initialized) {
return;
}
DEBUG && showDebugInfo("Initializing");
readPattern();
oldValue = iElement.val();
if (!oldValue) {
oldValue = "";
}
DEBUG && showDebugInfo("Original value:", oldValue);
bindListeners();
detectGetCaretPositionMethods();
detectSetCaretPositionMethods();
initialized = true;
}
function uninitialize() {
DEBUG && showDebugInfo("Uninitializing");
unbindListeners();
}
iAttrs.$observe("ngPatternRestrict", readPattern);
iAttrs.$observe("pattern", readPattern);
scope.$on("$destroy", uninitialize);
initialize();
};
}
};
}]);
Please note that it's also necessary to load this directive in the beginning:
var app = angular.module("myApp", ['ngPatternRestrict']);
As others have pointed out, you should solve this on the back-end by using prepared statements. It's the only way as the client can be edited relatively easily.
In Java, for example, you can use this:
PreparedStatement stmt = conn.prepareStatement("INSERT INTO student VALUES(?)");
stmt.setString(1, userInput);
stmt.execute();
This way the input is placed into the query as plain text, so SQL injection will not be an issue and Little Bobby Tables can go to your school.
input value to reflect the value in javascript input value to reflect the value in javascript input value to reflect the value in javascript input value to reflect the value in javascript
<div id="goodContent{{ entity.id}}" onclick="copyToClipboard();" style="display:none;">
{{ pdf_yolu }}
</div>
<div class="btn btn-default" id="clickCopy">Kopyala</div>
document.getElementById("clickCopy").onclick = function() {
copyToClipboard(document.getElementById("goodContent{{ entity.id}}"));
};
function copyToClipboard(e) {
var tempItem = document.createElement('input');
tempItem.setAttribute('type','text');
tempItem.setAttribute('display','none');
let content = e;
if (e instanceof HTMLElement) {
content = e.innerHTML;
}
tempItem.setAttribute('value',content);
document.body.appendChild(tempItem);
tempItem.select();
document.execCommand('Copy');
tempItem.parentElement.removeChild(tempItem);
}
This is not a Symfony issue as Symfony does not execute its own code on web browsers, which is where you need "copy to clipboard" functionality to run. (You should remove the Symfony tag from your question.) This is entirely JavaScript.
Consider a library such as ClipboardJS to do this. I can confirm it is usable on the front end templates of a Symfony based project.
In my case I had a table with many rows needing the 2nd column of each row to be copyable with a button. I wanted the button to appear in the first column. Here's the script I wrote:
Bare in mind I use other front end libraries too such as sprintf, jQuery, jQuery UI, Bootstrap 4, and FontAwesome. You should be able to adapt this though.
jQuery(document).ready(function($){
$('table').find('tr.js-copyable').each(function(k, v){
var $tr = $(v).first();
if ($tr.length != 1) {
return;
}
var $th = $tr.find('th').first();
if ($th.length != 1) {
return;
}
var $td = $tr.find('td').first();
if ($td.length != 1) {
return;
}
var value = $td.text();
if (typeof value != "string" || (value = value.trim()).length < 1) {
return;
}
var tdTooltip = function(text, icon){
if (typeof text != "string" || (text = text.trim()).length < 1) {
return;
}
if (typeof icon != "string" || (icon = icon.trim()).length < 1) {
icon = "";
}
$td.tooltip('dispose');
$td.tooltip({
html: true,
title: sprintf("<i class=\"fa %s\"></i><span>%s</span>", icon, text),
trigger: "manual",
placement: "left",
});
$td.tooltip('show');
setTimeout(function(){
$td.tooltip('hide');
}, 2000);
};
var $copyButton = $('<button class="btn btn-info js-copy js-tooltip" title="Copy to clipboard"><i class="fa fa-copy"></i></button>');
var clipboard = new ClipboardJS($copyButton[0], {
text: function(trigger){
$copyButton.tooltip('hide');
return value;
},
});
clipboard.on('success', function(e){
tdTooltip("Copied!", "fa-check-circle");
});
clipboard.on('error', function(e){
tdTooltip("Failed to copy.", "fa-times-circle");
});
$copyButton.appendTo($th);
});
});
Not one bit of the above has any wiff of Symfony about it. It's all JavaScript and associated front end libraries.
I'm trying to make the TAB key navigate on my dGrid. I have used as a base the solution found at Dgrid set focus on cell, but there are a couple of issues I'm running into which I couldn't solve so far.
Below you can find the block I'm using now; Not all columns have editors, so for I added a var do the element definition to select the next column instead of doing a right. I also added support for SHIFT+TAB to make backwards navigation possible. MT4.prje.grids[gridId]is the dGrid instance. There might be various on the page.
The grid is created with
MT4.prje.grids[gridId] = new (declare([OnDemandGrid, Keyboard, Selection, CellSelection]))(gridInfo, gridId);
where gridInfo has the column definitions and the store. The store is created as:
new Observable(new Memory({'data': {}, 'idProperty': 'id'}));
The editors are usually TextBox, NumberTextBox and Select dijit widgets, all set to autoSave.
aspect.after(MT4.prje.grids[gridId], "edit", function (promise, cellNode) {
if (promise === null) return;
promise.then(function (widget) {
if (!widget._editorKeypressHandle) {
widget._editorKeypressHandle = on(widget, "keypress", function (e) {
for (var rowId in MT4.prje.grids[gridId].selection) {
break;
}
for (var columnId in MT4.prje.grids[gridId].selection[rowId]) {
break;
}
if (e.charOrCode == keys.TAB) {
e.preventDefault();
var cellToEdit = null,
cellEdited = MT4.prje.grids[gridId].cell(rowId, columnId);
if (e.shiftKey) {
if (cellEdited.column.previousEditor === undefined) {
rowId = parseInt(rowId) - 1;
if (MT4.prje.grids[gridId].row(rowId).element !== null) {
for (var lastColumnId in MT4.prje.grids[gridId].columns) {}
cellToEdit = MT4.prje.grids[gridId].cell(rowId, lastColumnId);
}
} else {
cellToEdit = MT4.prje.grids[gridId].cell(rowId, cellEdited.column.previousEditor);
}
} else {
if (cellEdited.column.nextEditor === undefined) {
var firstColumnId = null;
rowId = parseInt(rowId) + 1;
if (MT4.prje.grids[gridId].row(rowId).element === null) {
var fields = {};
for (var cId in MT4.prje.grids[gridId].columns) {
if ((cId != 'excluir') && (firstColumnId === null)) {
firstColumnId = cId;
}
fields[cId] = '';
}
MT4.prje.addRowToGrid(gridId, fields);
} else {
for (var cId in MT4.prje.grids[gridId].columns) {
if (cId != 'excluir') {
firstColumnId = cId;
break;
}
}
}
cellToEdit = MT4.prje.grids[gridId].cell(rowId, firstColumnId);
} else {
cellToEdit = MT4.prje.grids[gridId].cell(rowId, cellEdited.column.nextEditor);
}
}
if (cellToEdit) {
MT4.prje.grids[gridId].deselect(cellEdited);
MT4.prje.grids[gridId].select(cellToEdit);
MT4.prje.grids[gridId].edit(cellToEdit);
}
}
});
}
});
});
Even ignoring the new line part, there are a couple of errors that happen. First of all, the editor barely pops into existence and them disappears, together with the selection. Sometimes when tabbing to an empty column, the editor will be filled with the values of the previous editor. Is there a way to do it more consistently?
What I'm figuring is that there is a race condition happening on the sharedEditor (they are set to editOn: focus). I tried wrapping the deselect/select on a dojo.on('blur') and emit it. But that doesn't get consistently correct with the dijit/form/Select widgets. Is there a better event that I can call for it?
I also tried changing the final block to:
if (cellToEdit) {
on(cellToEdit.element, 'focus', function(){
MT4.prje.grids[gridId].select(cellToEdit);
});
on(cellEdited.element, 'blur', function(){
MT4.prje.grids[gridId].deselect(cellEdited);
on.emit(cellToEdit.element, 'focus', {'bubble': true, 'cancelable': false});
});
on.emit(cellEdited.element, 'blur', {'bubble': true, 'cancelable': false});
}
But that gives two errors:
If I do make changes to a cell it does not go to the next editor. Does not even select it.
The first time I move from an empty cell to another empty cell it doesn't work either.
Anyone got any ideas?
This fix works on dgrid 0.3.11.
Add to your dgrid's postCreate.
postCreate: function() {
var that = this;
this.inherited(arguments);
this.on('dgrid-datachange', function(evt) {
that._selectedCell = that.cell(evt);
});
aspect.after(this, 'save', function(dfd) {
dfd.then(function() {
var nextCell = that.right(that.cell(that._selectedCell.row.id, that._selectedCell.column.id));
that.edit(nextCell);
// Bonus Fix. Workaround dgrid bug that blocks field text to be selected on focus.
nextCell.element.widget && nextCell.element.widget.textbox && nextCell.element.widget.textbox.select();
});
});
}
I am trying to use the typeWatch plugin for jQuery. I have this javascript:
<script type="text/javascript">
$(document).ready(function() {
var options = {
callback: function() { alert("a-ok! " + $(this).text); },
wait: 333,
highlight: true,
captureLength: 1
}
$("#customer").typeWatch(options);
});
</script>
And my view's HTML has this:
Method B: <%= Html.TextBox("customer") %>
With this test, if I type "ABC" in the textbox, I am expecting an alert to popup with "a-ok! ABC". Instead the following shows up...
a-ok! function (F) {
if (typeof F !== "object" && F != null) {
return this.empty().append((this[0] && this[0].ownerDocument ||
document).createTextNode(F));
}
var E = "";
o.each(F || this, function () {o.each(this.childNodes, function () {
if (this.nodeType != 8) {
E += this.nodeType != 1 ? this.nodeValue : o.fn.text([this]);}});});
return E;
}
I've tried changing the $(this).text to .val, and I've also tried referencing the input field more directly as $("#customer") but they yield similar results. How can I access just the entered text?
You should use the val() function on the textbox:
$(this).val();
Looking the code of typeWatch version 2.0 I found this:
function checkElement(timer, override) {
var elTxt = jQuery(timer.el).val(); <----------- !!! this...
// Fire if text > options.captureLength AND text != saved txt OR if override AND text > options.captureLength
if ((elTxt.length > options.captureLength && elTxt.toUpperCase() != timer.text)
|| (override && elTxt.length > options.captureLength)) {
timer.text = elTxt.toUpperCase();
timer.cb(elTxt); <-------------- !!! ...goes here.
}
};
timer.cb is the callback that you set up in the options. So you just add a parameter in that callback function that you use and that parameter will be the text from the input.