【问题标题】:How can I prevent the jQuery UI look'n'feel from disappearing after form submits/postbacks?如何防止 jQuery UI 外观在表单提交/回发后消失?
【发布时间】:2012-12-23 21:14:27
【问题描述】:

我有一个使用 jQuery datepicker 的 JSF (Mojarra) v2.1.11、Primefaces v3.4.2、Java 6 Web 应用程序。我使用的选择器看起来类似于:

$('#form1\\:dp').datepicker({showOn: 'button', buttonText: "Choose"});

这使用户能够单击按钮以调用日期选择器。我遇到的问题是“按钮”在用户提交表单后消失了。显然,“按钮”仅在页面最初加载时加载一次。我想知道(最佳实践是什么)如何在提交/回发之间保留 JQuery 日期选择器“按钮”。

index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      xmlns:p="http://primefaces.org/ui">
    <f:view contentType="text/html">
        <h:head>
            <title>testcal - index.xhtml</title>
            <meta charset="utf-8" />
        </h:head>
        <h:body>
            <h:form id="queryForm">
                <f:event type="postValidate" listener="#{testBean.validate}" />
                <p:panel id="queryPanel"  header="Test p:calendar, datepicker, validation, etc..." style="width:100%;">

                    <p:focus context="queryPanel"/>

                    <h:panelGroup id="msgs">
                        <p:message id="lastName_msg"    for="lastName"     style="display:none;"/>
                        <p:message id="birthDate_msg"   for="birthDate"    style="display:none;"/>
                        <p:message id="startDate_msg"   for="startDate"    style="display:none;"/>
                        <p:message id="endDate_msg"      for="endDate"     style="display:none;"/>
                        <p:message id="drpdwn_msg"       for="drpdwn"      style="display:none;"/>
                    </h:panelGroup>
                    <br/>
                    <br/>
                    <h:panelGroup id="querypanelgroup" style="display:inline-block;">
                        <p:focus context="querypanelgroup"/>

                        <h:panelGroup>
                            <h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
                                <p:outputLabel style="margin-right: 5px;"  value="Last Name:" for="lastName"/>
                            </h:panelGroup>
                            <h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
                                <p:inputText
                                    id="lastName"
                                    value="#{testBean.parmMap['lastName']}"
                                    requiredMessage="last name required"
                                    size="95"
                                    maxlength="95"
                                    onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(0).show();return false;" >
                                </p:inputText>
                            </h:panelGroup>
                        </h:panelGroup>

                        <br/>
                        <br/>

                        <h:panelGroup>
                            <h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
                                <p:outputLabel style="margin-right: 5px;"  value="Birth Date:" for="birthDate"/>
                            </h:panelGroup>
                            <h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
                                <p:inputText
                                    id="birthDate"
                                    value="#{testBean.parmMap['birthDate']}"
                                    requiredMessage="birth date required"
                                    converter="dpConverter"
                                    styleClass="datePicker"
                                    onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(1).show();$(this).mask('99/99/9999');return false;">
                                    <p:ajax event="change" process="@this" update="@this"/>
                                </p:inputText>
                            </h:panelGroup>
                        </h:panelGroup>

                        <br/>
                        <br/>

                        <h:panelGroup>
                            <h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
                                <p:outputLabel style="margin-right: 5px;"  value="Start Date:" for="startDate"/>
                            </h:panelGroup>
                            <h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
                                <p:inputText
                                    id="startDate"
                                    value="#{testBean.parmMap['startDate']}"
                                    requiredMessage="start date required"
                                    converter="dpConverter"
                                    styleClass="datePicker"
                                    onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(2).show();$(this).mask('99/99/9999');return false;">
                                    <!-- optional to populate another field with same value...
                                    onchange="$('...hashSymbolHere...queryForm\\:endDate').val($(this).val());">
                                    -->
                                    <p:ajax event="change" process="@this" update="@this"/>
                                </p:inputText>
                            </h:panelGroup>
                        </h:panelGroup>

                        <br/>
                        <br/>

                        <h:panelGroup>
                            <h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
                                <p:outputLabel for="endDate" value="Enter a date:"/>
                            </h:panelGroup>
                            <h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
                                <p:inputText
                                    id="endDate"
                                    value="#{testBean.parmMap['endDate']}"
                                    requiredMessage="endDate required"
                                    converter="dpConverter"
                                    styleClass="datePicker"
                                    onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(3).show();$(this).mask('99/99/9999');return false;">
                                    <p:ajax event="change" process="@this" update="@this"/>
                                </p:inputText>
                            </h:panelGroup>
                        </h:panelGroup>

                        <br/>
                        <br/>

                        <h:panelGroup>
                            <h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
                                <p:outputLabel for="drpdwn" value="Choose from drop down selction:">
                                    <h:panelGroup rendered="false"  style="margin-left: 2px;"  id="drpdwnRequired" styleClass="requiredInd">*</h:panelGroup>
                                </p:outputLabel>
                            </h:panelGroup>
                            <h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
                                <p:autoComplete
                                    id="drpdwn"
                                    style="overflow: hidden"
                                    maxResults="200"
                                    scrollHeight="150"
                                    dropdown="false"
                                    value="#{testBean.parmMap['drpdwn']}"
                                    completeMethod="#{testBean.drpdwnListComplete}"
                                    var="entry"
                                    itemLabel="#{entry.split(':')[1]}"
                                    itemValue="#{entry.split(':')[0]}"
                                    minQueryLength="1"
                                    forceSelection="true"
                                    onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(4).show();" >
                                </p:autoComplete>
                            </h:panelGroup>
                        </h:panelGroup>

                        <br/>
                        <br/>

                        <p:commandButton id="submit" value="Submit" oncomplete="applyDatePicker();" type="submit" update="@form" process="@form" action="#{testBean.submitQuery}" style="width:150px;" styleClass="button"/>
                        <p:commandButton value="Reset" update="@form" onclick="location.reload();return true;" process="@this" actionListener="#{testBean.reset}" immediate="true" ajax="false"/>

                    </h:panelGroup>
                </p:panel>
            </h:form>

            <h:outputStylesheet library="styles"    name="query.css"      />
            <h:outputScript      library="primefaces" name="/jquery/jquery.js" />
            <h:outputScript      library="primefaces" name="/jquery/plugins/ui/jquery-ui.custom.js" />
            <h:outputScript     library="primefaces" name="/jquery/plugins/inputmask/maskedinput.js" />
            <h:outputScript      library="js" name="testcal2.js" target="head" />


        </h:body>
    </f:view>
</html> 

TestBean.java

package aaa.bbb.ccc.war;

import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIForm;
import javax.faces.component.UIInput;
import javax.faces.component.UIPanel;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ComponentSystemEvent;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("testBean")
@Scope("view")
public class TestBean implements Serializable
{

    private static final List<String> drpdwnListOrig;  
    private static final String[] prfx = {"aaa","bbb","ccc", "ddd", "eee", "fff","ggg","hhh","iii","jjj","kkk","lll","mmm","nnn","ooo","ppp","qqq","rrr","sss","ttt","uuu","vvv","www","xxx","yyy","zzz"};

    //////////////////////////// [static initializer] ///////////////////////////////
    //////////////////////////// [static initializer] ///////////////////////////////
    //////////////////////////// [static initializer] ///////////////////////////////
    static
    {
        //drpdwnListOrig...
        List<String> l = getListOfStrings();
        drpdwnListOrig = Collections.unmodifiableList(null == l ? new ArrayList<String>() : l);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("drpdwnListOrig", drpdwnListOrig);
        List<String> testList = (List<String>) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("drpdwnListOrig");
    }

    public TestBean()
    {
        parmMap = this.getParmMap();
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parmMap", parmMap);
    }

    public void reset(ActionEvent event)
    {
        LinkedHashMap<String, Object> m = new LinkedHashMap<String, Object>();
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("parmMap");
        setParmMap(m);
    }

    public String submitQuery()
    {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("hitlistData");
        if (this.getParmMap().isEmpty())
        {
            return "";
        }

        return "/page2.xhtml?faces-redirect=true";
    }


    private static LinkedHashMap<String, Object> parmMap;
    public LinkedHashMap<String, Object> getParmMap()
    {
        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("parmMap");

        if (null == map)
        {
            map = new LinkedHashMap<String, Object>();
        }
        return map;
    }

    public void setParmMap(LinkedHashMap<String, Object> map)
    {
        parmMap = map;
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parmMap", parmMap);
    }


    private static SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    public void validate(ComponentSystemEvent e) throws ParseException
    {

        LinkedHashMap parmMap = this.getParmMap();
        UIForm queryForm = (UIForm) e.getComponent();

        UIInput lastName_c = (UIInput) queryForm.findComponent("lastName");
        String lastName = (String) (lastName_c.getValue());
        UIInput birthDate_c = (UIInput) queryForm.findComponent("birthDate");
        birthDate_c.setValid(true);
        String birthDate = (String) birthDate_c.getValue();

        FacesContext fc = FacesContext.getCurrentInstance();

        if (null != lastName && lastName.trim().length() > 0)
        {
            birthDate_c.setRequired(true);

            if (null == birthDate || birthDate.length() < 1)
            {
                birthDate_c.setValid(false);
                fc.addMessage(birthDate_c.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "birth date is required", "birth date is required"));
                fc.renderResponse();
            }
            else
            {
                birthDate_c.setValid(true);
            }
        }
        else
        {
            birthDate_c.setValid(true);
            birthDate_c.setRequired(false);
        }
    }

    //////////////////////////// autocomplete ///////////////////////////////    
    //////////////////////////// autocomplete ///////////////////////////////    
    //////////////////////////// autocomplete ///////////////////////////////    
    private static List<String> drpdwnList;

    public static List<String> getDrpdwnList()
    {
        if (null == drpdwnList)
        {
            drpdwnList = (null == drpdwnList ? (List<String>) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("drpdwnListOrig") : drpdwnListOrig);
        }

        return drpdwnList;
    }
    public void setDrpdwnList(List<String> data) throws IOException
    {
        drpdwnList = data;
    }
    public static List<String> drpdwnListComplete(String s)       //autocomplete "completeMethod"...
    {
        List<String> list = getDrpdwnList();
        List<String> drpdwnSuggestions = new ArrayList<String>();
        for (String ss : list)
        {
            if (ss.toLowerCase().contains(s.toLowerCase()))
            {
                drpdwnSuggestions.add(ss);
            }
        }
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("drpdwnSuggestions", drpdwnSuggestions);

        return drpdwnSuggestions;
    }


    //////////////////////////// get listbox values ///////////////////////////////
    //////////////////////////// get listbox values ///////////////////////////////
    //////////////////////////// get listbox values ///////////////////////////////
    public static List<String> getListOfStrings() //(String sql)
    {
        List<String> list = new ArrayList<String>();

        int ii=0;
        String key=null;
        String val=null;
        for (int i=0;i< 3500; i++)
        {

            if (ii > 25)
            {
                ii=0;
            }

            key = (i + "").trim();
            val = (i + prfx[ii]).trim();

            list.add(key + ":" + val);


            ii++;
        }

        return list;

    }    

}

testcal2.js

$(document).ready(function()
{
    applyDatePicker();
});


function applyDatePicker(){

    $('.datePicker').datepicker(
    {
        showOn: 'button', 
        buttonText: "Choose",
        showButtonPanel: true,
        showOptions: {direction: 'up'},
        changeYear: true,
        changeMonth: true,
        yearRange: "c-120:c+0"
    });
}

【问题讨论】:

  • 你想在f:ajax render之后调用$('#form1\\:dp').datepicker({showOn: 'button', buttonText: "Choose"});代码sn-p吗?你的意思是日期选择器失去了风格?要不然是啥 ?你如何提交表格?
  • 嗨 Daniel - 当页面首次呈现时,输入字段旁边有一个数据选择器按钮。提交页面时 - 在“回发”上 - 选择器显然不再处于活动状态并且按钮消失了。我需要“保留”按钮,以便用户在提交后不会看到它消失(尤其是在出现验证错误的情况下)。这有意义吗?让我知道是否需要进一步解释。谢谢! s
  • 您是否使用 f:ajax 提交?否则,如果您使用 f:ajax,您可以在 jquery 就绪函数中调用您的 js cofe,而不是查看 stackoverflow.com/a/10270872/617373
  • 嗨,Daniel - 我正在使用“$(document).ready”函数,并且我正在使用“p:commandButton”作为“提交”按钮...我已经添加我在上面测试的代码......你能更容易地看到我在哪里导致数据选择器“按钮”消失吗? (我不确定如何实施您提供的链接中的建议)。谢谢!
  • 将 datepicker 代码放到一个函数中,并在 jquery 就绪时调用该函数 + 在 p:commandButton 成功时调用该函数

标签: jquery-ui jsf-2 postback mojarra


【解决方案1】:

具体问题是因为您正在通过update="@form" 更新整个表单,导致jQuery UI 操作的输入元素也被重新渲染,导致jQuery UI 外观丢失。 $(document).ready() 不会在 ajax 请求上重新执行,因此输入元素保持“普通”。

这个问题基本上有两种解决方案:

  1. 不要在 ajax 响应中更新输入元素本身。 仅更新真正需要更新的部分。也许这只是信息?

    update="msgs"
    

    (顺便说一句,那些rendered="true"和style="display:none"很奇怪)

    如有必要,您可以指定多个以空格分隔的组件。

    update="msgs1 msgs2 msgs3"
    

    您也可以在您希望自动更新 ajax 响应的消息组件上使用 autoUpdate="true"。或者,如果有问题的组件不支持它,请将其包装在 &lt;p:outputPanel autoUpdate="true"&gt; 中。另见Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes。


  2. 在完成 ajax 请求后重新执行 jQuery UI 脚本。丹尼尔已经回答了这部分。 onsuccess 的替代方法是使用 OmniFaces'&lt;o:onloadScript&gt;。另见JSF/PrimeFaces ajax updates breaks jQuery event listener function bindings。

【讨论】:

  • 感谢您的帮助,BalusC!我意识到“document.ready”只执行了一次,但是,不太知道如何去持久化日期选择器/按钮。我会尝试采纳您和 Daniel 的建议,并让您知道结果。 (仅供参考 - 我提供的示例是从一个更大的应用程序中“删减”的。我使用奇怪的“msgs”面板组来显示与焦点字段相对应的消息。-我不想在字段旁边显示详细消息(是典型的实现),我不想在页面顶部显示所有消息的大列表。
  • rendered="true" 已经是默认值,但display:none 将其隐藏在客户端导致消息永远不会出现,所以这很奇怪。 JSF 将在实际有消息时呈现消息,因此 display:none 也没有任何意义。
  • Hi BalusC - 实际上任何与验证/等错误相对应的字段级别“”都会显示(字段消息标签将保留在此“div”中)。目前,我只希望显示与焦点字段相对应的字段级消息。我应该解释一下“rendered='true'”只是一个占位符。最终我想给用户一个选项来选择(A)字段(焦点)

    ,或(B)“全局”“

    ”(在这种情况下我会设置那个“占位符”渲染属性为“假”......假设这一切都有意义。再次感谢!

  • 再次感谢您,BalusC。 (顺便说一句 - 我选择了选项“2”)。不幸的是,我不允许灵活使用“Omnifaces”。再次感谢! s
  • 不客气。我扩展了选项 1 来讲述 autoUpdate,你可能没有意识到这一点。我仍然看不出有任何理由更新整个表单,包括这个特定用例中的输入字段。
【解决方案2】:

如果我没听错的话

将js代码放在函数中

function applyDatePicker(){
 $('#queryForm\\:dp2').datepicker(
    {
        showOn: 'button',
        buttonText: "Choose"
    });
}

拨打$(document).ready

$(document).ready(function()
{
   applyDatePicker();
});

也可以在&lt;p:commandButton中调用它

<p:commandButton onsuccess="applyDatePicker();"...

【讨论】:

  • 谢谢你,丹尼尔。我会尽快尝试你的建议,然后告诉你会发生什么
  • 你好丹尼尔。您的明确示例和 BalusC 的解释帮助我解决了这个问题。我制定了您的解决方案-唯一的区别是我使用了“oncomplete”而不是“onsuccess”-以便在部分回发等上保留“按钮”(我希望我正确使用了术语-如果没有,请原谅我)再次感谢!
  • 不客气。如果onsuccess 未到达,则意味着出现问题...您最好检查一下...
  • 嗨 Daniel - 我在“提交”“p:commandButton”中使用了“oncomplete”,因为我在控制器中执行“validate(ComponentSystemEvent e)”可能会发出“facesContext” .renderResponse”,当它检测到验证错误时。我不认为这被解释为“成功”。这没有意义吗? (再次感谢!)
  • ajax 提交成功与逻辑验证成功无关...所以验证失败根本不应该影响 ajax 提交的成功状态...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-23
  • 1970-01-01
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多