2014-01-03 6 views
0

У меня есть откуда я должен заполнить поля ввода, чтобы добавить нового клиента. Если я передам форму без ошибок в валидации, клиент будет добавлен в datatable, но если я попытаюсь добавить другого клиента, форма будет заполнена старыми значениями. Я попробовал скрипт ниже, но он не работает.Очистить форму после успешной проверки отправьте

<h:head>   
      <script> 
       function handleSubmitRequest(xhr, status, args, dialogName, formName) { 
        dialog = jQuery('#' + dialogName); 
        if (args.validationFailed) { 
         dialog.effect("shake", {times: 3}, 100); 
        } else { 
         customerDialogNew.hide(); 
        } 

       function clearForm(formName) { 
        jQuery('#' + formName).each(function() { 
         this.reset(); 
        }); 
       } 
      </script> 
     </h:head> 
    <h:form id="form">   
    <p:panel id="panelform" header="Customers" > 
        <p:dataTable value="#{customerMB.customers}" var="item" id="datas" rowsPerPageTemplate="5,10,15,20,25,30" 
            paginator="true" rows="10" filteredValue="#{customerMB.filteredCustomers}" 
             selectionMode="single" rowKey="#{item.id}" 
             selection="#{customerMB.selectedCustomer}"> 
         <p:ajax event="rowSelect" update=":form:dataView,:form:customerUpdate , :form:updateButton, 
     :form:viewButton" listener="#{customerMB.onRowSelect}"/> 
         <p:column headerText="Name" sortBy="#{item.name}" filterBy="#{item.name}" > 
          <p:outputLabel value="#{item.name}"/> 
         </p:column> 
         ... 
        </p:dataTable> 
     </h:form> 

<p:dialog draggable="true" header="New Customer" widgetVar="customerDialogNew" resizable="false" showEffect="clip" hideEffect="fold" style="position: absolute ;" id="dialog2">    
       <h:form id="newCustomerForm" > 
       <p:panelGrid id="newCustomer" columns="2" > 
        <p:focus context="newCustomer" /> 
        <f:facet name="header"> 
         <p:graphicImage value="/pictures/customerAdd.jpg"/> 
        </f:facet> 
        <p:outputLabel value="Name:" for="name" /> 
        <p:inputText id="name" value="#{customerMB.name}" title="Name" required="true" requiredMessage="The Name field is required."/>     
        <p:outputLabel value="FamilyName:" for="familyName" /> 
        <p:inputText id="familyName" value="#{customerMB.familyName}" title="FamilyName" required="true" requiredMessage="The FamilyName field is required."/> 
        <p:outputLabel value="Country:" for="country" /> 
        <p:inputText id="country" value="#{customerMB.address.country}" title="Country" required="true" requiredMessage="The Country field is required."/> 
        <p:outputLabel value="Town:" for="town" /> 
        <p:inputText id="town" value="#{customerMB.address.town}" title="Town" required="true" requiredMessage="The Town field is required."/> 
        <p:outputLabel value="Street:" for="street" /> 
        <p:inputText id="street" value="#{customerMB.address.street}" title="Street" required="true" requiredMessage="The Street field is required."/> 
        <p:outputLabel value="Zip Code:" for="zipcode" /> 
        <p:inputText id="zipcode" value="#{customerMB.address.zipCode}" type="number" title="zipcode" required="true" requiredMessage="The ZipCode field is required."/> 
        <p:outputLabel value="Status:" for="maritalstatus" /> 
        <p:selectOneMenu id="maritalstatus" value="#{customerMB.status}" required="true" requiredMessage="The Status field is required." > 
         <f:selectItem itemLabel="Select Status" itemValue="" /> 
         <f:selectItems value="#{customerMB.allStatuses}" /> 
        </p:selectOneMenu> 
        <p:outputLabel value="Gender:" for="sex" /> 
        <p:selectOneMenu id="sex" value="#{customerMB.sex}" required="true" requiredMessage="The Gender field is required."> 
         <f:selectItem itemLabel="Select Gender" itemValue="" /> 
         <f:selectItems value="#{customerMB.allGenders}" /> 
        </p:selectOneMenu>      
        <p:outputLabel value="Email:" for="email" /> 
        <p:inputText id="email" value="#{customerMB.email}" type="email" title="Email" required="true" validatorMessage="Insert a valid email" requiredMessage="The Email field is required."> 
         <f:validateRegex pattern="[\w\.-]*[a-zA-Z0-9_]@[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]" /> 
        </p:inputText> 
        <p:outputLabel value="Pseudo:" for="pseudo" /> 
        <p:inputText id="pseudo" value="#{customerMB.login}" title="Pseudo" required="true" requiredMessage="The Pseudo field is required."/> 
        <p:outputLabel for="pwd1" value="Password : " /> 
        <p:password id="pwd1" value="#{customerMB.password}" feedback="true" match="pwd2" label="Password 1" required="true" requiredMessage="The Password field is required."/> 
        <p:outputLabel for="pwd2" value="Confirm Password : " /> 
        <p:password id="pwd2" value="#{customerMB.password}" feedback="true" label="Password 2" required="true" requiredMessage="The confirm password field is required."/> 
        <p:outputLabel value="Right:" for="right" /> 
        <p:selectOneMenu id="right" value="#{customerMB.right}" required="true" requiredMessage="The Right field is required."> 
         <f:selectItem itemLabel="Select Right" itemValue="" /> 
         <f:selectItems value="#{customerMB.allRights}" /> 
        </p:selectOneMenu> 
       </p:panelGrid> 
       <p:commandButton style="height: 100%;width: 25%" value="Cancel" icon="ui-icon-arrowrefresh-1-n" onclick="customerDialogNew.hide();" >       
       </p:commandButton> 
       <p:commandButton styleClass="ui-priority-primary" style="height: 100%;width: 25%" value="Save" icon="ui-icon-circle-check" actionListener="#{customerMB.addNewCustomer()}" update=":form:panelform, newCustomer" oncomplete="handleSubmitRequest(xhr, status, args, 'customerDialogNew', 'newCustomerForm');">  
       </p:commandButton> 
      </h:form> 
     </p:dialog> 
+1

Вы можете просто использовать '' для этой цели –

+0

, когда я добавляю type = "reset" в inputText, он не работает, и я не могу даже писать в поле –

+0

его кнопка сброса, а не текстовое поле –

ответ

1

С вашего боба Session область действия. Объект bean, созданный для первого клиента, все еще присутствует на карте сеанса. Таким образом, каждый раз, когда загружается страница, вызывается получатель этого объекта, а поля на этой странице заполняются теми значениями, которые вы задали во время отправки последней формы. Вы можете изменить область своего компонента в RequestScope, если ваша страница не содержит данных, которые понадобятся во время сеанса пользователя. С помощью области запроса для каждого запроса создается новый экземпляр. Поэтому каждый раз, когда вы отправляете форму (для каждого запроса), текущие значения сохраняются и страница загружается с помощью нового экземпляра bean. Или вы можете очистить свойства в компоненте, соответствующие полям на странице, после сохранения данных из предыдущего представления.

0

Попробуйте это:

$('#form .form_element').each(function(){ 
    this.reset(); 
}); 
Смежные вопросы