How To Create Different Types Of Dynamic Input Fields In Form Using Jquery

In this article, We will learn about how to create different types of dynamic input fields in a form using jquery.

Normally, all are using the static input fields in the form. but if I want to add new input field types, we can create and add the input fields using jQuery.

Now, Let’s start to create a dynamic input field.

First of all, Create an index.php file and put the below HTML structure into this file for creating forms.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Blog Form</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
  <script src="js/custom.js"></script>
</head>
<body>
  <!-- Modal -->
  <div class="modal fade" id="inputModal" tabindex="-1" aria-labelledby="inputModalLabel" aria-hidden="true">
    <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
      <h5 class="modal-title" id="inputModalLabel">Add Input Field</h5>
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="form-group mb-2">
          <label for="field_type" class="form-label">Field Type</label><span class="text-danger">*</span>
          <select name="select" id="field_type" class="form-control">
            <option value="" selected>select</option>
            <option value="text">Text</option>
            <option value="number">Number</option>
            <option value="color">Color</option>
            <option value="checkbox">Checkbox</option>
            <option value="image">Image</option>
          </select>
          <div id="field_type_error" style="display:none"><font color="red">Please select field type.</font></div>
        </div>
        <div class="form-group mb-2">
          <label for="field_name" class="form-label">Field Name</label><span class="text-danger">*</span>
          <div class="input-group">
            <input name="field_name" id="field_name" placeholder="Enter Field Name" type="text" aria-describedby="fieldNamePrepend" class="form-control">
            <div class="input-group-prepend d-flex">
              <span class="input-group-text fieldname_prefix rounded-0 rounded-end" id="fieldNamePrepend">Select</span>
            </div>
          </div>
          <div id="field_name_error" style="display:none"><font color="red">Please enter field name.</font></div>
        </div>
        <div class="form-group">
          <input id="add-block-data-id" name="block-data-id" type="hidden" class="form-control">
        </div>
      </div>
      <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      <button type="button" id="add_input_field" name="add_input_field"  class="btn btn-primary">Insert</button>
      </div>
    </div>
    </div>
  </div>
  <!-- Form -->
  <div class="form-main-wrap pt-5">
    <form role="form" method="post" action="" id="add_app_ads_master" enctype="multipart/form-data" >
      <div class="row justify-content-center">
        <div class="col-xl-4 col-lg-6 col-md-6">
          <div class="card">
            <div class="card-header d-flex justify-content-between">
              <h5 class="card-title">Google Admob</h5>
              <div class="add-btn">
                <button type="button" class="btn btn-primary addbtn" data-id="google_admob" data-bs-toggle="modal" data-bs-target="#inputModal">
                  Add Input
                </button>
              </div>
            </div>
            <div class="card-body" id="google_admob">
              <div class="form-group mb-2 mb-2">
                <label for="app_open_admob" class="form-label">App Open Admob</label>
                <input name="app_open_admob" id="app_open_admob" placeholder="Enter App Open Admob" type="text" class="form-control">
              </div>
              <div class="form-group mb-2">
                <label for="banner_admob" class="form-label">Banner Admob</label>
                <input name="banner_admob" id="banner_admob" placeholder="Enter Banner Admob" type="text" class="form-control">
              </div>
              <div class="form-group mb-2">
                <label for="interstitial_admob" class="form-label">Interstitial Admob</label>
                <input name="interstitial_admob" id="interstitial_admob" placeholder="Enter Interstitial Admob" type="text" class="form-control">
              </div>
              <div class="form-group mb-2">
                <label for="interstitial_video_admob" class="form-label">Interstitial Video Admob</label>
                <input name="interstitial_video_admob" id="interstitial_video_admob" placeholder="Enter Interstitial Video Admob" type="text" class="form-control">
              </div>
            </div>
          </div>
        </div>
        <div class="col-xl-4 col-lg-6 col-md-6">
          <div class="main-card mb-3 card">
            <div class="card-header d-flex justify-content-between">
              <h5 class="card-title">Interstitial actvity flag</h5>
              <div class="add-btn">
                <button type="button" class="btn btn-primary addbtn" data-id="interstitial_actvity_flag" data-bs-toggle="modal" data-bs-target="#inputModal">
                  Add Input
                </button>
              </div>
            </div>
            <div class="card-body" id="interstitial_actvity_flag">
              <div class="form-group mb-2">
                <label for="activity_name" class="form-label">Activity Name</label>
                <input name="activity_name" id="activity_name" placeholder="Enter Activity Name" type="text" class="form-control">
              </div>
              <div class="row app-main-field" class="form-label">
                <label for="activity_flag"><input type="checkbox" name="activity_flag" id="activity_flag"> Activity Flag</label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</body>
</html>

Then, a js folder and create a custom.js file in the js folder. Now, add the below js in the custom js file.

This js file in add code for creating dynamic input fields.

jQuery(document).ready(function(){
  
  //Add data-id in input hidden field of form and Add the title in modal
  jQuery(document).on('click',".addbtn",function(event) {
    event.preventDefault();
    var dataid = jQuery(this).attr('data-id');
     jQuery('#'+dataid).slideDown();
    jQuery('#add-block-data-id').attr('value', dataid);
    var title_text = dataid.replace(/_/g,' ');
    var title_text = title_text.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase());
    jQuery('#inputModal #inputModalLabel').html("Add "+ title_text +" Input Field");
  }); 
  
  //On Change Append Type Of Field
  jQuery(document).on('change', '#field_type', function(event) {
    event.preventDefault();
    var typeVal = jQuery(this).val();
    let typeName;
    switch ( typeVal ) {
      case 'text':
        typeName = "";
        break;
      case 'number':
        typeName = "Count";
        break;
      case 'color':
        typeName = "Color";
        break;
      case 'checkbox':
        typeName = "Flag";
        break;
      case 'image':
        typeName = 'Image';
        break;
      default:
      typeName = "";
      break;
    }
    jQuery('#fieldNamePrepend').html( typeName );
  });
  
  // Create And Add A Dynamic Input Field into Form
  jQuery(document).on('click',"#add_input_field",function(event) {
    event.preventDefault();
    
    var field_type =  jQuery('#field_type').val();
    var fieldNamePrefix =  jQuery('#fieldNamePrepend').html();
    var fieldName =  jQuery('#field_name').val();
    var fielddata_id =  jQuery('#add-block-data-id').val();
    
    var field_name_joint = $.trim(fieldName).concat(" ", fieldNamePrefix);
    const field_name = field_name_joint.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase());
    
    var ret = true;
    if (!(field_type)){
            $( "#field_type_error" ).show();  
            ret = false;
        } else {
      $( "#field_type_error" ).hide();       
    }

    if (!(fieldName)){
            $( "#field_name_error" ).show();           
            ret = false;
        } else {
      $( "#field_name_error" ).hide();         
    }
    
    if( ret == true ){
      //convert string to lowercase and add ( - )
      var fieldname_lower = field_name.toLowerCase();
      field_name_split = fieldname_lower.split(' ').join('_');
      
      let fieldscript;
      switch ( field_type ) {
        case 'text':
          fieldscript = "<div class='form-group mb-2'><label for="+field_name_split+" class='form-label'>"+field_name+"</label><input name="+field_name_split+" id="+field_name_split+" placeholder='Enter "+field_name+"' type='text' class='form-control'></div>";
          break;
        case 'number':
          fieldscript = "<div class='form-group mb-2'><label for="+field_name_split+" class='form-label'>"+field_name+"</label><input name="+field_name_split+" id="+field_name_split+" placeholder='Enter "+field_name+"' type='number' class='form-control'></div>";
          break;
        case 'color':
          fieldscript = "<div class='form-group mb-2'><label for="+field_name_split+" class='form-label'>"+field_name+"</label><input name="+field_name_split+" id="+field_name_split+" placeholder='Enter "+field_name+"' type='color' class='form-control'></div>";
          break;
        case 'checkbox':
          fieldscript = "<div class='form-group mb-2'><label for="+field_name_split+" class='form-label'><input type='checkbox' name="+field_name_split+" id="+field_name_split+"> "+field_name+"</label></div>";
          break;
        case 'image':
          fieldscript = "<div class='form-group mb-2'><label for="+field_name_split+" class='form-label pe-2'>"+field_name+"</label><input class='form-control-file' type='file' name="+field_name_split+" id="+field_name_split+" accept='image/png ,image/PNG, image/gif, image/jpeg, image/webp' /></div>";
          break;
      }
      
      if( fieldscript != '' ){
        
        jQuery('#inputModal').modal('toggle');
        jQuery('#field_type, #field_name, #add-block-data-id').val('');
        jQuery('#fieldNamePrepend').html('Select');
        var addfield_id = jQuery('#'+fielddata_id);
        addfield_id.append(fieldscript);
      }
    }	
  }); 
});

Now you can see the output that forms in creating dynamic input fields of different input types.

Output:

Thank you, I hope you find something helpful.😃

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories