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

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.

Related

Input multiple with tags without autoCompletion

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

How to get the value of Liferay input editor in a javascript variable

In my application i am using liferay-ui:input-editor .I want to get the value of input editor to a javascript variable, How to achieve that?? I have tried
<liferay-ui:input-editor />
<input name="<portlet:namespace />htmlCodeFromEditorPlacedHere" type="hidden" value="" />
function createPopUp(){
var url ="<%=fetchCandidateByIdForPhoneURL%>";
var type= "fetchCandidateInfo";
var candidateId = $('#candidateID').val();
var jobId = $('#JobList').val();
var text1 = $('#text1').val();
var text2 = $('#text2').val();
var text3 = $('#text3').val();
var interviewVenue = $('#interviewVenue').val();
var interviewCC = $('#interviewCC').val();
var interviewBCC =$('#interviewBCC').val();
var startDate = $('#start-date').val();
var interviewType = $('#interviewType').val();
var x ;
function <portlet:namespace />initEditor() {
return '<font style="font-weight: bold">scott was here</font>';
}
function <portlet:namespace />extractCodeFromEditor() {
var x = document.<portlet:namespace />fm.<portlet:namespace />htmlCodeFromEditorPlacedHere.value = window.<portlet:namespace />editor.getHTML();
alert(x);
}
But it is showing that
ReferenceError: _InterviewSchedule_WAR_InterviewScheduleportlet_initEditor is not defined error. How to resolve it and get the value in a javascript variable
Given the information provided in question, it seems that the javascript initialization function is missing for <liferay-ui:input-editor />. As pointed out in the tutorial here, which OP seems to be using (juding by variable names):
By default, the editor will call "initEditor()" to try and pre-populate the body of the editor. In this example, when the editor loads, it will have the value of "scott was here" in bold.
(...)
function <portlet:namespace />initEditor() {
return '<font style="font-weight: bold">scott was here</font>';
}
By default, the ck editor that Liferay uses will try to call the initEditor() javascript method to try and pre-populate the contents of the editor.
Therefore, you should define such a method, even if you return a blank string.
An example is given below:
<aui:script>
function <portlet:namespace />initEditor() {
return "<%= content %>";
}
</aui:script>
, where content is the string variable with the content you want to pass in when the editor is loaded. If you do not want to pass initial content then simply pass a black string.

Allow only digits to the filtered textbox (search filter) of dataTable in Primefaces

Is it possible to apply such a validation to a filtered textbox provided by dataTable of Primefaces by customizing it.
The maximum number of characters that this textbox can hold can be set by using the filterMaxLength="45" property of <p:column>. For example.
<p:column headerText="headerText" sortBy="#{obj.properyName}" filterMaxLength="45" filterBy="#{obj.properyName}">
<h:outputText value="#{obj.properyName}" />
</p:column>
I can't see such a property to perform other kind of validations such as allowing only specific characters, perhaps by using a regex.
Anyway, I need to allow it to have only digits, since there an id column of the type BIGINT (primary key, auto-increment) in MySQL database which is mapped to the Long datatype in entity classes.
Is it supported by Primefaces or is there a way to customize it?
AFAIK Primefaces doesn't has this option. You can use javascript to solve that.
You have to set id for column that you want to limit, the input(use for filter) have default id is filter, then you process keydown event to allow only digits. for example, i create one form(id="form"), and nest one datatable(id="cars"),one column(id="cl2") and input's id is filter, then i bind keydown event to filter the key which user type:
<h:form id="form">
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
$("#form\\:cars\\:cl2\\:filter").keydown(function(event) {
// Allow: backspace, delete, tab, escape, and enter
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
});
//]]>
</script>
<p:dataTable id="cars">
<p:column id="cl2" headerText="MANUFAC" filterMatchMode="contains" filterBy="#{carr.manufacturer}">
</p:dataTable>
See also: How to allow only numeric (0-9) in HTML inputbox using jQuery?
Extending Rong Nguyens answer.
In your javascript method, to find the Filter component. Rather than navigating down the DOM tree elements, you can use filterStyleClass attribute on p:column.
Here is an example:
<p:column id="cl2" headerText="MANUFAC" filterStyleClass="filterNumbersOnly" filterMatchMode="contains" filterBy="#{carr.manufacturer}">
And in your JS method you can use that class to get element:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
$(".filterNumbersOnly").keydown(function(event) {
//Your logic to restrict numbers only goes here
}
})
</script>
The advantage is since this method is CSS class based element selection.
You can write this JS function once in your application and apply this class as: filterStyleClass="filterNumbersOnly" on any number of columns throughout your application or page.

How to write an inputText accepting only integers in the #,###.00 pattern

Is there any way of writing an inputText which is only accepting digits and also in the #,###.00 pattern format for inputting a currency number in JSF ? (using PrimeFaces will be more appreciated)
Thanks...
Check this link
Here says you can use:
<p:inputMask value="# {maskController.date}" mask="99/99/9999"/>
I never used PrimeFaces before but i've used JSF. If you dont want to use javascript, you need to use a convert tag inside of the inputText tag.
<h:inputText id="money" required="true">
<f:convertNumber maxFractionDigits="2"
groupingUsed="true"
currencySymbol="$"
maxIntegerDigits="4"
type="currency"/>
</h:inputText>
PD: RegEx is another option. RegEx means Regular Expression. It is a way to check if something like an string matches with a rule. You can use in jsf with the RegEx Validator.
This below code is working
<script>
<![CDATA[
function isNumber(event) {
if (event) {
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode < 48 || charCode > 57)
return false;
}
return true;
}
]]>
</script>
<p:inputText id="money" onkeydown="return isNumber(event);" />
to erase key available
<script>
<![CDATA[
function isNumber(event) {
if (event) {
var charCode = (event.which) ? event.which : event.keyCode;
if ((charCode < 48 || charCode > 57) && charCode!=8 && charCode!=46)
return false;
}
return true;
}
]]>
</script>
<p:inputText id="money" onkeydown="return isNumber(event);" />
Adding additional helpful not listed answer for this question :
Simply you can use primefaces extension tag inputNumber :
https://www.primefaces.org/showcase/ui/input/inputNumber.xhtml

Drupal - Search box not working - custom theme template

I am using a customised version of search-theme-form.tpl
When I use the search box, I do get transferred to the search page. But the search does not actually take place. The search box on the search results page does work though. This is my search-them-form.tpl.php file (demo :
<input type="text" name="search_theme_form_keys" id="edit-search-theme-form-keys" value="Search" title="Enter the terms you wish to search for" class="logininput" height="24px" onblur="restoreSearch(this)" onfocus="clearInput(this)" />
<input type="submit" name="op" id="edit-submit" value="" class="form-submit" style="display: none;" />
<input type="hidden" name="form_token" id="edit-search-theme-form-form-token" value="<?php print drupal_get_token('search_theme_form'); ?>" />
<input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form" />
There is also a javascript file involved. I guess it's use is pretty clear from the code:
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function clearInput(e) {
e.value=""; // clear default text when clicked
e.className="longininput_onfocus"; //change class
}
function restoreSearch(e) {
if (trim(e.value) == '') {
{
e.value="Search"; // reset default text onBlur
e.className="logininput"; //reset class
}
}
}
What can be the problem and how can I fix it?
Apparently, you cannot directly modify the HTML in search-theme-form.tpl.php since thats not the right way to do it. So my adding the class and onFocus and onBlur attributes was the problem.
The correct way to do it is to modify the themes template.php file. Basically we will be using form_alter() to modify the form elements. Since using the HTML way is wrong. Take a look at the code below (taken from : here )
<?php
/**
* Override or insert PHPTemplate variables into the search_theme_form template.
*
* #param $vars
* A sequential array of variables to pass to the theme template.
* #param $hook
* The name of the theme function being called (not used in this case.)
*/
function yourthemename_preprocess_search_theme_form(&$vars, $hook) {
// Note that in order to theme a search block you should rename this function
// to yourthemename_preprocess_search_block_form and use
// 'search_block_form' instead of 'search_theme_form' in the customizations
// bellow.
// Modify elements of the search form
$vars['form']['search_theme_form']['#title'] = t('');
// Set a default value for the search box
$vars['form']['search_theme_form']['#value'] = t('Search this Site');
// Add a custom class and placeholder text to the search box
$vars['form']['search_theme_form']['#attributes'] = array('class' => 'NormalTextBox txtSearch',
'onfocus' => "if (this.value == 'Search this Site') {this.value = '';}",
'onblur' => "if (this.value == '') {this.value = 'Search this Site';}");
// Change the text on the submit button
//$vars['form']['submit']['#value'] = t('Go');
// Rebuild the rendered version (search form only, rest remains unchanged)
unset($vars['form']['search_theme_form']['#printed']);
$vars['search']['search_theme_form'] = drupal_render($vars['form']['search_theme_form']);
$vars['form']['submit']['#type'] = 'image_button';
$vars['form']['submit']['#src'] = path_to_theme() . '/images/search.jpg';
// Rebuild the rendered version (submit button, rest remains unchanged)
unset($vars['form']['submit']['#printed']);
$vars['search']['submit'] = drupal_render($vars['form']['submit']);
// Collect all form elements to make it easier to print the whole form.
$vars['search_form'] = implode($vars['search']);
}
?>
In yourthemename_preprocess_search_theme_form - 'yourthemename' will obviously reflect the name of your custom theme. Basically the code is self-explanatory. what with the comments and all.
So, basically thats the way it works.

Resources