-2

Am using JSF and Primefaces .. And i need when i focus on the outlabel the input text gets background color This is my code :


<p:panelGrid columns="2" layout="grid" style="border:0px none;background:none" styleClass="ui-panelgrid-blank ">
   <p:outputLabel value="#{msg.PurchaseReturns_Txt_Document_NO}"   />
   <p:inputText readonly="true" value="#{quotationMB.instance.object.quotationid}"/>
</p:panelGrid>

<p:panelGrid styleClass="datePick ui-panelgrid-blank " columns="2" layout="grid"  style="border:0px none;background:none">
   <p:outputLabel value="#{msg.RequestForQuotation_Txt_Date}" />
   <p:calendar  value="#{quotationMB.instance.object.validto}" locale="de" navigator="true" pattern="yyyy-MMM-dd" showOn="button" />
</p:panelGrid>

*************************JAVA Script*******************************

I have tried this code .. It worked but on the whole input texts that i have in my page :


 $('.ui-outputlabel').click(function() {
    $(this).find('.ui-inputtext').css('background-color', 'red');
});

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
Mustafa Fahmy
  • 65
  • 1
  • 1
  • 10

1 Answers1

2

There are a few things wrong in your question.

To start off, you cannot focus a p:outputLabel (which is rendered as an HTML label). Clicking the label will focus the linked field. Which brings us to the second issue.

In order for an p:outputLabel to work as specified in the showcase (validation errors, error styling, required indicator, etc.), you need to use the for attribute to link it to the input component (as in regular HTML).

So, if you add for to your labels, you can simply style the input fields using the :focus CSS selector.

Technically you could get your click listener working like this (but that would not make sense):

$("label").click(function(){
    document.getElementById(this.htmlFor).style.backgroundColor = "red";
});

It would make more sense to add a focus and blur listener to input fields and use the listeners to toggle a CSS class on the corresponding label. For example:

$("input").focus(function(){
    $("label[for=\""+ this.id +"\"]").addClass("focus");
});
$("input").blur(function(){
    $("label[for=\""+ this.id +"\"]").removeClass("focus");
});

See also:

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
  • This idea came through to my head at the beginning .. But i have to add "for" for the whole input fields that i have one by one .. So is there any other solution ? – Mustafa Fahmy May 30 '17 at 07:53
  • You could create a custom tag which combines the two. See https://stackoverflow.com/questions/5713718/how-to-make-a-grid-of-jsf-composite-component – Jasper de Vries May 30 '17 at 07:56
  • 1
    .. but without `for` your labels are pretty much useless. I would advice to add them, even if it requires a bit of work. – Jasper de Vries May 30 '17 at 08:01