如何使用JQuery动态添加Primefaces输入字段

时间:2014-01-22 17:46:51

标签: jquery jsf-2 primefaces

我正在尝试从Primefaces动态添加标签和文本字段到我的网页。 我想使用JQuery。到目前为止,我只使用Primefaces实现了相同的任务,并且它运行良好,但我想避免一些行为。

<!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">

 <h:head>
<script type="text/javascript">

      $(document).ready(function() {
         var counter = 2;   

         $("#addButton").click(function(){

        var newTextBoxDiv = $(document.createElement('div')).attr("id",'TextBoxDiv' + counter);


            <!--
               This line causes trouble. If I use it nothing is rendered on page. 
               If I use <h:inputText /> the page is rendered but the functionality does
               not work
            -->
            newTextBoxDiv.html("<p:inputText />"); 
        newTextBoxDiv.appendTo("#TextBoxesGroup");
        counter++;
         });
      });
   </script>

</h:head>

<h:body>

<ui:insert>
    <ui:include src="/protected/header.xhtml" />
</ui:insert>


<h:form>
    <div id="test"></div>
    <div id='TextBoxesGroup'></div>
    <input type='button' value='Add Button' id='addButton' />
    <input type='button' value='Remove Button' id='removeButton' />
</h:form>
</h:body>
</html>

我会很感激关于这个主题的教程的一些提示,或者我的代码中是否是一个简单的错误。这个问题的解决方案。提前谢谢你:)

1 个答案:

答案 0 :(得分:6)

看起来你完全错过了JSF的观点,而且对Web开发来说还是个新手。 JSF是一个服务器端语言/框架,它生成HTML代码(在浏览器中右键单击页面并执行查看源代码,您现在看到它吗?没有单个JSF标记,它是一个和所有HTML)。 jQuery是一种客户端语言,仅适用于HTML DOM树。 <p:inputText>不是已知的HTML元素。浏览器不知道如何处理它。它只知道像<input>和朋友那样的HTML。

您需要以“JSF-ish”的方式挽救功能需求。这是一个启动示例:

<h:form>
    <ui:repeat value="#{bean.items}" var="item">
        <p:outputLabel for="foo" value="#{item.label}" />
        <p:inputText id="foo" value="#{item.value}" />
        <p:commandButton value="Remove" action="#{bean.remove(item)}" update="@form" />
        <br/>
    </ui:repeat>
    <p:commandButton value="Add" action="#{bean.add}" update="@form" />
</h:form>

@ManagedBean
@ViewScoped
public class Bean implements Serializable {

    private List<Item> items;

    @PostConstruct
    public void init() {
        items = new ArrayList<>();
    }

    public void add() {
        Item item = new Item();
        item.setLabel("label" + items.size());
        items.add(item);
    }

    public void remove(Item item) {
        items.remove(item);
    }

    public List<Item> getItems() {
        return items;
    }

}

public class Item {

    private String label;
    private String value;

    // Let your IDE generate getters/setters/equals/hashCode.
}

这就是全部。通过添加指向save()方法的另一个命令按钮,将所有内容都准备好在服务器端进行保存,并将items变量进一步传递给EJB / service / DAO类。

否则,如果你真的想用jQuery方式做,那么你应该完全放弃JSF并去寻找像Spring MVC这样的基于请求的东西。你只需要记住,你自己要写下所有的HTML / CSS / JS。

另见: