Input multiple with tags without autoCompletion - jsf

I have two inputs.
I want the two inputs to have the same look and feel see below:
The first input use autocomplete and allows the user to select a list of terms => I use p:autocomplete (see Primefaces documentation on autocomplete)
This input works fine.
For the second input, I would like to have the same display but without any autocompletion : the user just enter a list of terms with no autocompletion at all.
I tried to have a fake autocomplete that return the value given by the user but it is too slow and the behaviour is not correct when the user quit the input.
Any idea is welcome.

After a quick look at the PrimeFaces javascript code of the autoComplete and a few hours experimenting with it, I came up with a solution. It involves overriding the bindKeyEvents and in it deciding to call the original one or not, adding detection for the space key ('selecting a tag') and when pressed, add the tag and fire the selectionEvent (if ajax is used). Place the following code in your page or in an external javascript file
<script>
//<![CDATA[
if(PrimeFaces.widget.AutoComplete) {
PrimeFaces.widget.AutoComplete = PrimeFaces.widget.AutoComplete.extend ( {
bindKeyEvents: function() {
if (this.input.attr('data-justTags')) {
var $this = this;
this.input.on('keyup.autoComplete', function(e) {
var keyCode = $.ui.keyCode,
key = e.which;
}).on('keydown.autoComplete', function(e) {
var keyCode = $.ui.keyCode;
$this.suppressInput = false;
switch(e.which) {
case keyCode.BACKSPACE:
if ($this.cfg.multiple && !$this.input.val().length) {
$this.removeItem(e, $(this).parent().prev());
e.preventDefault();
}
break;
case keyCode.SPACE:
if($this.cfg.multiple) {
var itemValue = $this.input.val();
var itemDisplayMarkup = '<li data-token-value="' +itemValue + '"class="ui-autocomplete-token ui-state-active ui-corner-all ui-helper-hidden">';
itemDisplayMarkup += '<span class="ui-autocomplete-token-icon ui-icon ui-icon-close" />';
itemDisplayMarkup += '<span class="ui-autocomplete-token-label">' + itemValue + '</span></li>';
$this.inputContainer.before(itemDisplayMarkup);
$this.multiItemContainer.children('.ui-helper-hidden').fadeIn();
$this.input.val('').focus();
$this.hinput.append('<option value="' + itemValue + '" selected="selected"></option>');
if($this.multiItemContainer.children('li.ui-autocomplete-token').length >= $this.cfg.selectLimit) {
$this.input.css('display', 'none').blur();
$this.disableDropdown();
}
$this.invokeItemSelectBehavior(e, itemValue);
}
break;
};
});
} else {
//console.log("Original bindEvents");
this._super();
}
}
});
}
//]]>
</script>
For deciding on when to call the original one or not, I decided to use a passThrough attribute with a data-justTags name. e.g. pt:data-justTags="true" (value does not matter, so pt:data-justTags="false" is identical to pt:data-justTags="true"). A small html snippet of this is:
<p:autoComplete pt:data-justTags="true" multiple="true" value="#{myBean.selectedValues}">
And do not forget to add the xmlns:pt="http://xmlns.jcp.org/jsf/passthrough" namespace declaration.

I found a component that could do the job : http://www.butterfaces.org/tags.jsf

Related

Decouple navigation and selection with JSF tree-like widget

I'm looking for a good approach to realize a tree-like JSF widget with the following requirements:
means to expand and collapse tree branches
ajax navigation through clicking on a tree node
multi-selection of nodes / branches via tri-state checkboxes
the former three features must work independent from each other
the solution must be compatible with PrimeFaces
I don't want to fork the framework in terms of writing a custom component
What I've come across:
PrimeFaces p:tree and p:treeTable
built-in selection feature provides a nice implementation with tri-state checkboxes but is tightly coupled to clicking on a node, which makes it unusable in terms of navigation (the selection also changes)
alternatively a custom implementation of the checkbox-column must reinvent the whole tri-state checkbox logic even with pe:triStateCheckbox (PrimeFaces Extensions)
OmniFaces o:tree seems to offer a high level of customization, but also leaves a lot of needle crafting remaining
Any hints, experiences are welcome.
I ended up with a solution build on p:treeTable with selectionMode="checkbox" and p:commandLink for navigation.
To disable the 'full row' mouse click trigger also causing selection changes the JavaScript has been adjusted like this (PrimeFaces 5.3):
<script type="text/javascript">
//<![CDATA[
PrimeFaces.widget.TreeTable.prototype.bindSelectionEvents = function() {
var $this = this,
rowSelector = '> tr.ui-treetable-selectable-node';
this.tbody.off('mouseover.treeTable mouseout.treeTable click.treeTable', rowSelector)
.on('mouseover.treeTable', rowSelector, null, function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
element.addClass('ui-state-hover');
if($this.isCheckboxSelection() && !$this.cfg.nativeElements) {
element.find('> td:first-child > div.ui-chkbox > div.ui-chkbox-box').addClass('ui-state-hover');
}
}
})
.on('mouseout.treeTable', rowSelector, null, function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
element.removeClass('ui-state-hover');
if($this.isCheckboxSelection() && !$this.cfg.nativeElements) {
element.find('> td:first-child > div.ui-chkbox > div.ui-chkbox-box').removeClass('ui-state-hover');
}
}
})
.on('click.treeTable', rowSelector, null, function(e) {
//$this.onRowClick(e, $(this));
e.preventDefault();
});
if(this.isCheckboxSelection()) {
var checkboxSelector = this.cfg.nativeElements ? '> tr.ui-treetable-selectable-node > td:first-child :checkbox':
'> tr.ui-treetable-selectable-node > td:first-child div.ui-chkbox-box';
this.tbody.off('click.treeTable-checkbox', checkboxSelector)
.on('click.treeTable-checkbox', checkboxSelector, null, function(e) {
var node = $(this).closest('tr.ui-treetable-selectable-node');
$this.toggleCheckboxNode(node);
});
//initial partial selected visuals
if(this.cfg.nativeElements) {
this.indeterminateNodes(this.tbody.children('tr.ui-treetable-partialselected'));
}
}
};
//]]>
</script>
I also changed some CSS, mainly:
.ui-treetable .ui-treetable-data tr.ui-state-highlight,
.ui-treetable .ui-treetable-data tr.ui-state-hover {
cursor: default;
}

How to disable special characters and alphabets in Primefaces input text?

I want a <p:inputText> which should only accept numbers and not any other characters. Is it possible so that the user can only type in numbers and the other characters are disabled? If so, please let me know how.
In the end, the <h:inputText> and <p:inputText> components will render an <input type="text" /> HTML component. The only thing you need is to apply a JavaScript method to restrict the characters that will be allowed in the text.
Knowing this, you can use any of the methods provided in the question HTML Text Input allow only Numeric input. I'll show you an example based on the second answer of the post:
<h:head>
<script type="text/javascript">
//<![CDATA[
var numericRegex = /\d+\.?\d*/;
function validateNumericInput(evt, text) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
if (key === '.') {
theEvent.returnValue = (text.indexOf(key) < 0);
} else {
var regex = /\d/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
}
//]]>
</script>
</h:head>
<h:body>
Try to write a non-numeric
<p:inputText onkeypress="validateNumericInput(event, this.text)" />
</h:body>
Note that this example only allows to write positive real numbers, just change the JavaScript method to define a different behavior.

AngularJS : How to say to a directive to clone scope?

I have this fiddle, and can not make this work. I believe that the reason resides in that two li elements with a custom directive edit-in-place share scope.
The solution would be to say to the directive to create a copy of the scope that binds on the parent - can transclude help?
angular.module('bla', [])
.directive('editInPlace', ['$parse','$compile', function($parse, $compile) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attribs) {
var inputStart = '<input style="border: 2 solid black" name="inPlaceInput" style="display:none" value="';
var inputEnd = '">';
scope.editModeAccessor = $parse(attribs.editInPlace);
scope.modelAccessor = $parse(attribs.ngBind);
scope.$watch(attribs.editInPlace, function(newValue, oldValue){
if (newValue){
console.debug("click");
console.debug("value: " + scope.modelAccessor(scope));
var inputHtml = inputStart + scope.modelAccessor(scope) + inputEnd;
element.after(inputHtml);
jQuery(element).hide();
scope.inputElement = jQuery("input[name=inPlaceInput]");
scope.inputElement.show();
scope.inputElement.focus();
scope.inputElement.bind("blur", function() {
blur();
});
} else {
blur();
}
});
function blur(){
console.debug("blur secondary");
if (scope.inputElement){
console.debug("blur secondary inputElement found");
var value = scope.inputElement.val();
console.debug("input value: "+ value);
scope.inputElement.remove();
jQuery(element).show();
scope.editModeAccessor.assign(scope, false);
scope.modelAccessor.assign(scope, value);
}
}
}
}
}]);
function ContactsCtrl($scope, $timeout){
$scope.contacts = [{number:'+25480989333', name:'sharon'},{number:'+42079872232', name:''}];
$scope.editMode = false;
var editedId;
$scope.edit = function(id){
$scope.editMode = true;
jQuery("#"+id).hide();
editedId = id;
//TODO show delete button
}
$scope.$watch('editMode', function(newValue, oldValue){
if (!newValue && editedId){
jQuery("#"+editedId).show();
}
});
}
<div ng-app="bla">
<div ng-controller="ContactsCtrl">
<h4>Contacts</h4>
<ul>
<li ng-repeat="contact in contacts">
<span edit-in-place="editMode" ng-bind="contact.number"></span>
<span edit-in-place="editMode" ng-bind="contact.name"></span>
<span id="{{$index}}" ng-click="edit($index)"><i class="icon-edit">CLICKtoEDIT</i></span>
</li>
</ul>
</div></div>
I think cloning the scope is not the best solution.
When creating a directive in angular, you should encapsulate all the functionality within the directive. You should also avoid mixing jQuery in when you don't have to. Most of the time (as in this case) you're just introducing unnecessary complexity. Lastly, classes are the best way of controlling display, rather than the style attribute on an element.
I took the liberty of rewriting your directive in a more "angular" way - with no jQuery. As you can see from the updated jsFiddle, it is simpler and cleaner. Also, it works!
This directive can be easily modified to add lots of additional awesome functionality.
app.directive( 'editInPlace', function() {
return {
restrict: 'E',
scope: { value: '=' },
template: '<span ng-click="edit()" ng-bind="value"></span><input ng-model="value"></input>',
link: function ( $scope, element, attrs ) {
// Let's get a reference to the input element, as we'll want to reference it.
var inputElement = angular.element( element.children()[1] );
// This directive should have a set class so we can style it.
element.addClass( 'edit-in-place' );
// Initially, we're not editing.
$scope.editing = false;
// ng-click handler to activate edit-in-place
$scope.edit = function () {
$scope.editing = true;
// We control display through a class on the directive itself. See the CSS.
element.addClass( 'active' );
// And we must focus the element.
// `angular.element()` provides a chainable array, like jQuery so to access a native DOM function,
// we have to reference the first element in the array.
inputElement[0].focus();
};
// When we leave the input, we're done editing.
inputElement.prop( 'onblur', function() {
$scope.editing = false;
element.removeClass( 'active' );
});
}
};
});

Kendo UI - Placeholder - Style

I have a Kendo UI datepicker with placeholder data. Here is the HTML:
<input type="text" class="datepicker"' placeholder="yyyy-mm-dd" />
Here is the JavaScript:
var start = $(".datepicker").kendoDatePicker({
format: "yyyy-MM-dd",
parseFormats: ["MM/dd/yyyy"],
change: startChange
}).data("kendoDatePicker");
The Kendo UI datepicker displays the placeholder data in the same style as user entered data. I would like to style the placeholder data differently. Specifically, I would like the text to be gray and italicized. When user enters data, the style changes to solid black (non-italicized). Any thoughts on how to do this?
Well, placeholder is an HTML5 attibute and isn't specic to Kendo controls. As I understand it Kendo doesn't offer any support for placeholder over what is supported by the browser, and remember that only some browsers support this attribute; IE does not.
Anyway, to style the placeholder you'll have to use vendor prefix CSS properties, see here.
I use this..it will work on your HTML and you can style it too :)
<script>
// This adds 'placeholder' to the items listed in the jQuery .support object.
jQuery(function() {
jQuery.support.placeholder = false;
test = document.createElement('input');
if('placeholder' in test) jQuery.support.placeholder = true;
});
// This adds placeholder support to browsers that wouldn't otherwise support it.
$(function() {
if(!$.support.placeholder) {
var active = document.activeElement;
$(':text').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text').blur();
$(active).focus();
$('form:eq(0)').submit(function () {
$(':text.hasPlaceholder').val('');
});
}
});
</script>

Allow only Copy/Paste Context Menu in System.Windows.Forms.WebBrowser Control

The WebBrowser control has a property called "IsWebBrowserContextMenuEnabled" that disables all ability to right-click on a web page and see a context menu. This is very close to what I want (I don't want anyone to be able to right-click and print, hit back, hit properties, view source, etc).
The only problem is this also disables the context menu that appears in TextBoxes for copy/paste, etc.
To make this clearer, this is what I don't want:
This is what I do want:
I would like to disable the main context menu, but allow the one that appears in TextBoxes. Anyone know how I would do that? The WebBrowser.Document.ContextMenuShowing event looks promising, but doesn't seem to properly identify the element the user is right-clicking on, either through the HtmlElementEventArgs parameter's "FromElement" and "ToElement" properties, nor is the sender anything but the HtmlDocument element.
Thanks in advance!
have you considered writing your own context menu in javascript? Just listen to the user right clicking on the body, then show your menu with copy and paste commands (hint: element.style.display = "block|none"). To copy, execute the following code:
CopiedTxt = document.selection.createRange();
CopiedTxt.execCommand("Copy");
And to paste:
CopiedTxt = document.selection.createRange();
CopiedTxt.execCommand("Paste");
Source:
http://www.geekpedia.com/tutorial126_Clipboard-cut-copy-and-paste-with-JavaScript.html
NOTE: This only works in IE (which is fine for your application).
I know its not bulletproof by any means, but here is a code sample that should get you started:
<html>
<head>
<script type = "text/javascript">
var lastForm = null;
window.onload = function(){
var menu = document.getElementById("ContextMenu");
var cpy = document.getElementById("CopyBtn");
var pst = document.getElementById("PasteBtn");
document.body.onmouseup = function(){
if (event.button == 2)
{
menu.style.left = event.clientX + "px";
menu.style.top = event.clientY + "px";
menu.style.display = "block";
return true;
}
menu.style.display = "none";
};
cpy.onclick = function(){
copy = document.selection.createRange();
copy.execCommand("Copy");
return false;
};
pst.onclick = function(){
if (lastForm)
{
copy = lastForm.createTextRange();
copy.execCommand("Paste");
}
return false;
};
};
</script>
</head>
<body oncontextmenu = "return false;">
<div id = "ContextMenu" style = "display : none; background: #fff; border: 1px solid #aaa; position: absolute;
width : 75px;">
Copy
Paste
</div>
sadgjghdskjghksghkds
<input type = "text" onfocus = "lastForm = this;" />
</body>
</html>
//Start:
function cutomizedcontextmenu(e)
{
var target = window.event ? window.event.srcElement : e ? e.target : null;
if( navigator.userAgent.toLowerCase().indexOf("msie") != -1 )
{
if (target.type != "text" && target.type != "textarea" && target.type != "password")
{
alert(message);
return false;
}
return true;
}
else if( navigator.product == "Gecko" )
{
alert(message);
return false;
}
}
document.oncontextmenu = cutomizedcontextmenu;
//End:
I hope this will help you Anderson Imes
A quick look at the MSDN documentation shows that none of the mouse events (click, button down/up etc) are supported to be used in your program. I'm afraid its either or: Either disable conetxt menus, or allow them.
If you disable them, the user can still copy & paste using keyboard shortcuts (Ctrl-C, Ctrl-V). Maybe that gives you the functionality you need.
We ended up using a combination of both of the above comments. Closer to the second, which is why I gave him credit.
There is a way to replace the context menu on both the client-side web code as well as through winforms, which is the approach we took. I really didn't want to rewrite the context menu, but this seems to have given us the right mix of control.

Resources