jQuery - Create hidden form element on the fly

In this tutorial, we'll understand how to create a hidden form element in DOM using jQuery?
Submitted by Pratishtha Saxena, on August 11, 2022

So, in order to make any input field of the form hidden, we need to pass an attribute "hidden" as its input type. Adding this in any input field will make that particular field of the form hidden.

Syntax:

$("<input>").attr("type", "hidden").appendTo("form");

Now, if this task has to be done dynamically using jQuery, then this field must be added to the form when the document gets ready. To add/create a hidden input field, we will append this into the form using the appendTo() method of jQuery.

Syntax:

$(content).appendTo(selector);

Since we are clear with the syntaxes and their usage, let's move on to an example for better understanding.

Code to create hidden form element on the fly using jQuery

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Title</title>
  </head>
  <body>
    <form>
      <label>Name: </label>
      <input type="text"> <br><br>
      <label>Age</label>
      <input type="number"><br><br>
      <label>Email: </label>
      <input type="email"><br><br>
      Hidden:
    </form>
  </body>
</html>

jQuery:

$(document).ready(function() {
    $('<input>').attr({
        type: 'hidden',
        id: 'gender',
        name: 'Gender'
    }).appendTo('form');
})

Output:

This hidden input field can be viewed in the elements section after inspecting the page.

Example: Create hidden form element on the fly





All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.