jquery存储容器内容以及变量中的表单选择

时间:2017-05-24 15:33:27

标签: jquery html html-select html-form

我不确定这是可能的,所以让我知道如果我问不可能,但我有一个JSP页面,其中包含一个绑定到spring MVC模型的表单。 我有一个按钮,当点击时,在javascript变量中存储div的内容。表单包含在此div中。然后将div内容替换为其他HTML。这是JSP页面......

<input id="linkEntity" type="button" value="Link" />
<input id="storeDiv" type="button" value="store" />

<div id="div1">
    <form:form id="form1" method="post" modelAttribute="model" action="${pageContext.servletContext.contextPath}/save">
        <select name="ethnicity" >
            <option value="">Please select</option>
                <c:forEach items="${ethnicityList}" var="et">
                    <option value="${et.code}" <c:if test="${et.code == model.ethnicity}">selected="selected"</c:if>>${et.desc}</option>
                </c:forEach>
        </select>
    </form:form>
</div>
<script type="text/javascript">
    $( document ).ready(function() {
        var origDiv = "";
        $("body").on("click", "#storeDiv", function() {
            origDiv = $("#div1").html();
            $("#div1").html("replace div with other contents..");
        });
        $("body").on("click", "#linkEntity", function() {
            $("#div1").html(origDiv );
        });

    });
</script>

我想要发生的是,如果在select元素中进行了选择,我能以某种方式记录这个并在用原始HTML替换div内容时选择该值吗?

2 个答案:

答案 0 :(得分:0)

$( document ).ready(function() {
    var origDiv = $("#div1").html();
    $("body").on("click", "#storeDiv", function() {
        $("#div1").html("replace div with other contents..");
    });
    $("body").on("click", "#linkEntity", function() {
        $("#div1").html(origDiv );
    });
});

答案 1 :(得分:0)

这是一个解决方案...... 在页面加载时创建另一个名为formselections的空js变量。

var formselections = "";

在原始html存储在js变量中的点,使用..填充另一个带有表单值的js变量。

formselections = $("#form1").serializeArray();

然后当您将原始html放回容器中时,迭代此变量将表单元素设置为记录值,如下所示。

$.each(formselections, function(i, e) {
    $("#form1 [name="+e.name+"]").val(e.value);
}); 
相关问题