jQuery - Create hidden form element on the fly
Asked Answered
K

6

362

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

Komi answered 9/3, 2010 at 9:53 Comment(0)
F
683
$('<input>').attr('type','hidden').appendTo('form');

To answer your second question:

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'bar'
}).appendTo('form');
Fluvial answered 9/3, 2010 at 10:2 Comment(6)
Note that IE will choke if you attempt to change the input type after it's created. Use $('<input type="hidden">').foo(...) as a workaround.Piston
Also, jQuery documentation suggests that since DOM manipulation is expensive, if you have multiple inputs to be added, add all of them once using something like $(this).append(hidden_element_array.join(''));Delldella
I just tried this method with jQuery 1.6.2 and recieved this error with Firefox 7.0.1: "uncaught exception: type property can't be changed" It seems that you cant use the attr method to change the type property under these conditions. I'm now trying the method below...Difference
Will this same approach work with the newer .prop function in the newer API release?Grader
@Grader .prop is not "the new .attr" as a lot of people seems to think. You should still use .attr to set attributes.Fluvial
I had trouble with this approach when I tried to add valid HTML for the input field, as I was unable to add either a </input> or <input /> type of field. If anyone knows a solution, that would be very helpfulConvolvulus
M
155
$('#myformelement').append('<input type="hidden" name="myfieldname" value="myvalue" />');
Mcrae answered 9/3, 2010 at 9:56 Comment(3)
Did someone test this answer on old IE?Aircrew
Personally, I believe this is a much better approach than the accepted answer as it involves less DOM manipulation/function calls.Fontanez
@Fontanez For the given case, yes you are correct, but it isn't always so. Take a look here https://mcmap.net/q/93748/-which-is-better-string-html-generation-or-jquery-dom-element-creationAccompanyist
M
45

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

$('<input>', {
    type: 'hidden',
    id: 'foo',
    name: 'foo',
    value: 'bar'
}).appendTo('form');
Murraymurre answered 19/11, 2015 at 14:47 Comment(3)
Is there a name for this way of populating a tag?Arianna
how to append the input only 1 time? if its exist it keep entering new value with same attributeUpholstery
Very streamlined, I love it.Perrin
B
29

if you want to add more attributes just do like:

$('<input>').attr('type','hidden').attr('name','foo[]').attr('value','bar').appendTo('form');

Or

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'foo[]',
    value: 'bar'
}).appendTo('form');
Babin answered 30/6, 2014 at 15:11 Comment(2)
this is giving console error Unexpected identifier .Brownedoff
Second code, seems the "id" need to be generated dynamically something like foo1, foo2 etcMediocre
C
8
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;
    theForm.appendChild(input);
}

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

// Add data:
addHidden(theForm, 'key-one', 'value');
Caryopsis answered 24/9, 2014 at 7:17 Comment(1)
What is the 'name-as-seen-at-the-server'?Prate
P
2

Working JSFIDDLE

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">
</form> 
    <br><br>   
    <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

$(document).ready(function(){

    $("#add-input").on('click', function(){
        $('#hidden-element-test').prepend('<input type="hidden" name="ipaddress" value="192.168.1.201" />');
        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

Psychopathy answered 11/7, 2014 at 8:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.