You can create a jQuery function to do most of the work for you. I use this function to add hidden inputs programatically:
jQuery Function:
// 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));
}
});
};
Usage:
For standard form items or simple parameters in MVC theHidden as String:
$('#myform').addHidden('theHidden', 'jam');
=> <input type="hidden" name="theHidden" value="jam">
For list parameters in 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">
For complex types in MVC which have a List property model As ComplexType:
$('#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
$("<input id='thehidden' type='hidden' name='thehidden' value='hiddenval' />")- you left off your closing slash.$('#thehidden')or only for the return of$('#thehidden').val()?