2

I am rendering a <p:outputLabel>, when validation failed like this.

<p:outputLabel value="Validation Failed"
               styleClass="validation-error"
               rendered="#{facesContext.validationFailed}" 
               onfocus="myMethod();"/>

I want to execute a JavaScript function namely myMethod(), when this label is rendered. I also used onfocus attribute but it doesn't work.

Tiny
  • 27,221
  • 105
  • 339
  • 599
Undertaker
  • 111
  • 2
  • 13

1 Answers1

2

Ignoring potential design problems (perhaps you actually need a document event listener?), you can achieve this by simply nesting a <script> (or <h:outputScript>) in the component.

<p:outputLabel ...><script>myFunction()</script></p:outputLabel>

I only renamed "myMethod" to "myFunction" conform JavaScript terminology.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks @BlausC this has solved my problem. Can you explain why onfocus attribute is not working? – Undertaker Aug 12 '15 at 14:04
  • You're welcome. It works only when the element gets focus. The element doesn't automagically get focus when it's simply being added to DOM. The enduser has to focus it manually (or you have to run some JavaScript to trigger focus event on that, but that's nonsense as you could as good immediately invoke that function instead). – BalusC Aug 12 '15 at 14:05
  • It's great, but can I refer to the component with a variable? Thanks. – László Tóth Aug 14 '23 at 13:20
  • 1
    @László: https://stackoverflow.com/q/6045307 – BalusC Aug 19 '23 at 18:02