I have the following simple Javascript code that allows only digits to be entered into the specified TextField
. I have used it earlier in many places such as Servlet, JSP, JSTL/EL and even in PHP and it worked fine as expected. In JSF however, I less concerned with Javascript in which some characters need to be escaped. I tried my best to get it run but I couldn't. Here is the Javascript code along with JSF stuff.
<?xml version='1.0' encoding='UTF-8' ?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Demo</title>
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$("#myForm:txtDemo").keypress(function(event)
{
if (event.keyCode==46 || event.keyCode==8|| event.keyCode==9 || event.keyCode>=35 && event.keyCode<=40)
{
// let it happen, don't do anything
}
else
{
if (event.charCode<48 || event.charCode>57 || event.charCode==16)
{
event.preventDefault();
}
}
});
});
</script>
</h:head>
<h:body>
<h:form id="myForm">
<br/><br/><br/>
<h:inputText id="txtDemo" required="true" requiredMessage="Mandatory." validatorMessage="The field should contain al least 10 digits">
<f:validateLength maximum="10" minimum="2"/>
<f:validateRegex pattern="[0-9]*"/>
<f:ajax event="valueChange" execute="txtDemo msg" render="txtDemo msg"/>
</h:inputText><br/>
<h:message id="msg" for="txtDemo" showDetail="true" style="color:red"/><br/>
<h:commandButton id="btnSubmit" value="Submit"/>
</h:form>
</h:body>
Javascript is not being compiled. It parses the following error.
An Error Occurred:
Error Parsing /Restricted/TempTags.xhtml: Error Traced[line: 14] The entity name
must immediately follow the '&' in the entity reference.
I have even placed the Javascript code in a separate js
file and included that file in this page. I have also replaced <script></scrip>
with <h:outputScript></h:outputScript>
still the same problem remains.
I have also tried the following to see whether the Javascript function is being called or not using alert();
removing the error parsing code from the function but the function itself wasn't even called and the alert message wasn't displayed.
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$("#myForm:txtDemo").keypress(function(event)
{
alert();
});
});
</script>
Which necessary changes are required in that Javascript to get it run as expected?