jQuery – Create hidden form element on the fly

jQuery – Create hidden form element on the fly

What is the simplest way to dynamically create a hidden input form field using jQuery?


Solution 1:


To answer your second question:

    type: 'hidden',
    id: 'foo',
    name: 'bar'

Solution 2:

$('#myformelement').append('<input type="hidden" name="myfieldname" value="myvalue" />');

Solution 3:

if you want to add more attributes just do like:



    type: 'hidden',
    id: 'foo',
    name: 'foo[]',
    value: 'bar'

Solution 4:

The same as David’s, but without attr()

$('<input>', {
    type: 'hidden',
    id: 'foo',
    name: 'foo',
    value: 'bar'

Solution 5:

function addHidden(theForm, key, value) {
    // Create a hidden input element, and append it to the form:
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key;'name-as-seen-at-the-server';
    input.value = value;

// Form reference:
var theForm = document.forms['detParameterForm'];

// Add data:
addHidden(theForm, 'key-one', 'value');

Solution 6:


If your form is like

<form action="" method="get" id="hidden-element-test">
      First name: <input type="text" name="fname"><br>
      Last name: <input type="text" name="lname"><br>
      <input type="submit" value="Submit">
    <button id="add-input">Add hidden input</button>
    <button id="add-textarea">Add hidden textarea</button>

You can add hidden input and textarea to form like this


    $("#add-input").on('click', function(){
        $('#hidden-element-test').prepend('<input type="hidden" name="ipaddress" value="" />');
        alert('Hideen Input Added.');

    $("#add-textarea").on('click', function(){
        $('#hidden-element-test').prepend('<textarea name="instructions" style="display:none;">this is a test textarea</textarea>');
        alert('Hideen Textarea Added.');


Check working jsfiddle here