JQuery以编程方式添加隐藏元素

时间:2010-04-08 15:32:42

标签: javascript jquery

现在我真的得到了。我有一个在页面加载时加载的表单。在我的jquery中 'ready'函数我在这个表单中附加了一个隐藏的内容:

$("<input id='thehidden' type='hidden' name='thehidden' value='hiddenval'>").appendTo("#MenuForm")

当我用firebug检查表单内容时,我可以看到添加了元素。

["$(\"#MenuForm\").children()"] is [div, input#thehidden hiddenval]

到目前为止一切都很好。当我提交这个表格并再次阅读elemet时,我无法获得我添加的新隐藏值的值。

alert($('#thehidden').val())

未定义

任何帮助将不胜感激

4 个答案:

答案 0 :(得分:3)

您究竟何时尝试从#thehidden div读取值?当按下提交按钮或提交后页面重新加载?如果您不是每次在页面加载时都创建输入,那么下一页加载就不会存在。

我测试了你的代码,只是创建输入并在警报中读回值,它对我来说很好。 Check it out为你自己。

答案 1 :(得分:2)

$('#someid').append($('<input></input>').attr('id','hidden1').attr('type','hidden').attr('value','some val'));

答案 2 :(得分:2)

您可以创建一个jQuery函数来完成大部分工作。我使用此函数以编程方式添加隐藏的输入:

jQuery功能:

// This must be applied to a form (or an object inside a form).
jQuery.fn.addHidden = function (name, value) {
    return this.each(function () {
        var input = {};
        if (Object.prototype.toString.call(value) === '[object Array]') {
            var r = /\[\]/;
            // Pass an array as a series of separate hidden fields.
            for (var i = 0; i < value.length; i++) {
                input = $("<input>").attr("type", "hidden")
                                    .attr("name", name.replace(r, '[' + i + ']'))
                                    .val(value[i]);
                $(this).append($(input));
            }
        } else {
            input = $("<input>").attr("type", "hidden")
                                .attr("name", name)
                                .val(value);
            $(this).append($(input));
        }
    });
};

用法:

对于MVC theHidden as String中的标准表单项或简单参数:

$('#myform').addHidden('theHidden', 'jam');
=> <input type="hidden" name="theHidden" value="jam">

对于MVC ID As List(Of Integer)中的列表参数:

$('#myform').addHidden('ID', [1,2,5]);
=> <input type="hidden" name="ID" value="1">
   <input type="hidden" name="ID" value="2">
   <input type="hidden" name="ID" value="4">

对于具有List属性model As ComplexType的MVC中的复杂类型:

$('#myform').addHidden('Customer[].CustomerID', [1,2,5]);
=> <input type="hidden" name="Customer[0].CustomerID" value="1">
   <input type="hidden" name="Customer[1].CustomerID" value="2">
   <input type="hidden" name="Customer[2].CustomerID" value="5">
Class ComplexType
    Property Customer As List(Of CustomerDetail)
End Class
Class CustomerDetail
    Property CustomerID As Integer
End Class

答案 3 :(得分:-1)

您需要将输入ELEMENT插入DOM,而不仅仅是将HTML注入页面。对于表单字段,存在差异。

使用var field = $(document.createElement('input')),然后设置字段的属性。

相关问题