The Wayback Machine - https://web.archive.org/web/20240828193603/https://www.geeksforgeeks.org/design-a-form-component-which-takes-input-from-its-user-and-displays-a-form/
Open In App

Design a form component which takes input from its user and displays a form

Last Updated : 14 Feb, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Design: Here are the things that it should support:

  • Grouping of the fields of the form
  • Validations for fields
  • Submit button

For example, the user might want to validate if the input is a valid address and might want this component to have default validations for email, etc.
Let’s try to create a very basic data model for our component.

For our minimalistic implementation, we might want to use these fields.

  • Id: The id for the field
  • Type: text/dropdown etc
  • Subtype: For input type text we might want password etc
  • Values: for dropdown/Radio
  • Validator: the custom validator provided by the user. We can use the value of “email” etc to provide default validation.
  • Group: the group to which this field should belong
  • Placeholder: placeholder if needed for the field.
  • Handler: to provide a callback/option for the submit button click

For this, we would try to use the MVC pattern in JS. First, let’s develop our model class.

For our minimalistic implementation, we will keep the input for this component in our model class.
Our model will have input for the component which will be hardcoded now and an event that will notify that our input has changed.
Here is the minimalistic implementation




function ListModel() {
    this._formInput=[ {
        "id": "id1",
        "type":"text",
        "name":"name",
        "placeholder":"name",
        "values":"",
        "validator":function () {
            console.log("test1");
        }
        ,
        "group":"gr1"
    }
    ,
    {
        "id": "id2",
        "type":"dropdown",
        "name":"name",
        "placeholder":"name",
        "values":[1,
        2,
        3],
        "validator":function () {
            console.log("test2");
        }
        ,
        "group":"gr2"
    }
    ,
    {
        "id": "id3",
        "type":"radio",
        "name":"name",
        "placeholder":"name",
        "values":["male",
        "female"],
        "validator":function () {
            console.log("test");
        }
        ,
        "group":"gr3"
    }
    ,
    {
        "id":"id4",
        "type":"button",
        "name":"name",
        "placeholder":"name",
        "values":"",
        "handler": function () {
            console.log("test3");
        }
        ,
        "group":"gr3"
    }
    ];
    this.itemAdded=new Event(this);
}
  
ListModel.prototype= {
    addItem: function () {
        this.itemAdded.notify();
    }
    ,
    getFormInput: function () {
        return [].concat(this._formInput);
    }
    ,
}
  
;


Here the event class is basic pub/sub implementation where each module can react to an event. Here is the event class




function Event(sender) {
    this._sender = sender;
    this._listeners = [];
}
Event.prototype = {
    attach: function(listener) {
        this._listeners.push(listener);
    },
    notify: function(args) {
        var index;
        for (index = 0; index < this._listeners.length; index += 1) {
            this._listeners[index](this._sender, args);
        }
    }
};


Now coming to our controller. For our sample use case, we have triggered items added to the model on controller initialization only.
Below is the class:




function ListController(model, view) {
    this._model = model;
    this._view = view;
    var _this = this;
    _this.returnResult();
}
ListController.prototype = {
    returnResult : function () {
        this._model.addItem();
    }
};


Now coming to our main class which will eventually render the form which is our view class.

Here is the view class:




function ListView(model) {
    this._model = model;
    var _this = this;
    this._model.itemAdded.attach(function () {
        _this.addResult();
    });
    this._validators = [];
}


Here we store the model(which in our case is the input to this component) and the validators for each field.
Also, we attach the event handler to our model change which will create the view. Here is the complete code




ListView.prototype = {
    addResult: function() {
        var data = this._model.getFormInput();
        this.createContent(data);
    },
    createContent: function(data) {
        var totalFieldGroup = [];
        var fieldGroup = [];
        var groups = {};
        for (var itr = 0; itr < data.length; itr++) {
            if (!totalFieldGroup.includes(data[itr]["group"]))
                totalFieldGroup.push(data[itr]["group"]);
            if (typeof data[itr]["validator"] == "function")
                this._validators.push(data[itr]["validator"]);
        }
        var form = document.createElement("form");
        for (var j = 0; j < totalFieldGroup.length; j++) {
            fieldGroup.push(data.filter(function(individual) {
                if (individual["group"] == totalFieldGroup[j]) {
                    return true;
                } else {
                    return false;
                }
            }));
            var fieldset = document.createElement("fieldset");
            var legend = document.createElement("legend");
            legend.innerHTML = fieldGroup[0][0]["group"];
            fieldset.appendChild(legend);
            this.createComponent(fieldGroup, fieldset);
            form.appendChild(fieldset);
            fieldGroup = [];
        }
        var subbtn = data.filter(function(individual) {
            if (individual["type"] == "button") {
                return true;
            } else {
                return false;
            }
        });
        if (subbtn.length == 0) {
            alert("no submit button found");
            return;
        }
        var btn = this.addSubmitButton(subbtn, form);
        form.appendChild(btn);
        form.setAttribute("id", "parentForm");
        document.body.appendChild(form);
    },
    addSubmitButton: function(subbtn, form) {
        var x = document.createElement("button");
        x.setAttribute("type", "submit");
        x.innerHTML = "Submit";
        var self = this;
        x.addEventListener("click", function() {
            for (var i = 0; i < self._validators.length; i++) {
                self._validators[i]();
            }
            subbtn[0]["handler"]();
            form.submit();
        });
        return x;
    },
    createComponent: function(fieldGroup, fieldset) {
        var ret = fieldset;
        for (var i = 0; i < fieldGroup.length; i++) {
            switch (fieldGroup[0][i].type) {
                case "text":
                    var label = document.createElement("label");
                    label.innerHTML = fieldGroup[0][i].name;
                    var x = document.createElement("INPUT");
                    x.setAttribute("type", "text");
                    x.setAttribute("placeholder", 
                                   fieldGroup[0][i].placeholder);
                    x.setAttribute("id", fieldGroup[0][i].id);
                    fieldset.append(label);
                    fieldset.append(x);
                    break;
                case "dropdown":
                    var label = document.createElement("label");
                    label.innerHTML = fieldGroup[0][i].name;
                    var select = document.createElement("select");
                    select.setAttribute("id", fieldGroup[0][i].id);
                    for (var k = 0; k < fieldGroup[0][i].values.length; k++) {
                        var option = document.createElement("option");
                        option.innerHTML = fieldGroup[0][i].values[k];
                        select.appendChild(option);
                    }
                    select.setAttribute("placeholder", 
                                        fieldGroup[0][i].placeholder);
                    fieldset.append(label);
                    fieldset.append(select);
                    break;
                case "radio":
                    var label1 = document.createElement("label");
                    label1.innerHTML = fieldGroup[0][i].name;
                    var label = document.createElement("radiogroup");
                    for (var k = 0; k < fieldGroup[0][i].values.length; k++) {
                        var radio = document.createElement("input");
                        radio.type = "radio";
                        radio.label = fieldGroup[0][i].values[k];
                        radio.innerHTML = fieldGroup[0][i].values[k];
                        radio.value = fieldGroup[0][i].values[k];
                        label.appendChild(radio);
                    }
                    label1.appendChild(label);
                    fieldset.append(label1);
                    break;
            }
        }
    }
};


Here is how we instantiate the component




window.onload = function() {
    var model = new ListModel([]),
        view = new ListView(model),
        controller = new ListController(model, view);
};


Output:



Similar Reads

How to write a program that takes a predicate and array, like Array.filter(), but only keeps x if pred(x) === false in JavaScript ?
The predicate in JavaScript is the same as the predicate maths which returns true or false. The predicate is just like a function that determines whether the passed arguments satisfy the given condition or not. The predicate returns only true or false. In this article, let us see the working of the predicate with arrays when it is passed with a fun
3 min read
How to define the duration of an animation takes to complete in CSS ?
When designing a website, JavaScript is generally used to define behavior for the web pages. But there are ways, which help us to define certain behavior for the page using CSS. One such behavior is animation. CSS animations are the methods that help us to change the behavior and appearance of a web page without using JavaScript. They define the ap
2 min read
Bulma Button Displays
Bulma is an open-source CSS framework that provides pre-built components which can be combined together to make responsive websites and web applications. We can choose the display of buttons in Bulma as per our choice. Mainly there are four displays of buttons is available in Bulma. Bulma Displays Class: Normal: Button has a normal display as by de
2 min read
Which input type is used to hide the input field to be displayed in HTML Form ?
The form tag is generally used to create forms for entering data. We can use different form tag attributes like text boxes, text area, checkboxes, radio buttons, buttons, dropdown list, etc. to collect data from the users. We need to use the HTML &lt;input type=”hidden”&gt; type for hiding the input field. Using this attribute, the input field will
1 min read
How to define a form for user input using HTML5 ?
In this article, we will learn how to create a form in a webpage by using the &lt;form&gt; tag. This tag is used to create form for user input. Also there are many elements which are used within form tag. Syntax: &lt;form&gt; Form Content... &lt;/form&gt; Example: The following code snippet demonstrates the simple creation of form. &lt;!DOCTYPE htm
1 min read
User to User private Chat App using ReactJS and Firebase | Without socket programming
This article covers how to make a User to User private Chat App using React JS and Firebase (without socket programming). React is a JavaScript framework provided by Facebook and is used to build fully-featured web applications. We will be following the below steps for creating our application: npx create-react-app chat-appcd chat-appNow install al
10 min read
ReactJS UI Ant Design Input Component
Ant Design Library has this component pre-built, and it is very easy to integrate as well. Input Component is used to create a basic widget for getting the user input is a text field. We can use the following approach in ReactJS to use the Ant Design Input Component. Input Props: addonAfter: It is used to denote the label text displayed after the i
4 min read
How to validate and sanitize user input with PHP?
Data validation is an integral part of web development, especially while working with forms where the user first enters their personal data and then sends that to the database. Data sent in an invalid format can cause DBMS security problems. Hackers often use SQL injections to insert malicious SQL commands into the database. SQL injections can even
4 min read
Which attribute is used to disabled the specific input field in HTML Form ?
HTML5 introduced many attributes that are used for developing an efficient webpage. In this article, we will learn to disable the particular input field by using the "disable" attribute with the specific type of input. The disabled attribute is a boolean attribute that is used to vandalize the input field. A disabled input is un-clickable and unusa
1 min read
How to take user input for two dimensional (2D) array in PHP ?
There are two methods to take user input in PHP in two dimensional (2D) array. Approach 1: Use HTML forms through PHP GET &amp; POST method to take user input in two dimensional (2D) array.First, input data into HTML forms.Then use the GET or POST method of PHP to get or post those input data into a variable.Finally, use that variable that holds in
3 min read
Convert user input string into regular expression using JavaScript
In this article, we will convert the user input string into a regular expression using JavaScript.To convert user input into a regular expression in JavaScript, you can use the RegExp constructor. The RegExp constructor takes a string as its argument and converts it into a regular expression object Regular expressions (RegExp) are patterns used to
2 min read
How to sanitize user input to URL with an amp-bind-macro call ?
Introduction: Sometimes you may want to sanities your input to the search URL of the Google, this can be achieved with the help of amp-bind-macro. It can be used to create a sanitized URL dynamically. A sanitized URL can be achieved by simply converting the input to lowercase and replacing the spaces with '%20'. Setup: To use amp-bind-macro in our
2 min read
How to specify that a user can enter more than one value in an input element in HTML5?
The multiple attribute is used to specify whether the user can enter more than one value in an input element. It is a Boolean attribute. When set to true, the input element can accept more than one value. The multiple properties can be used in the following ways. With the &lt;input&gt; tag only the Email and File type accepts the multiple attribute
2 min read
Handling User Input in Vue.js
Vue.js is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. Handling User Input in Vue.js: Use
4 min read
How to Filter an Array based on user input in AngularJS ?
AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a &lt;script&gt; tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. Angular filters can be added in AngularJS to format data. In this article, we will be discussing how to filt
3 min read
How to Sort an Array based on User Input in AngularJS ?
AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a &lt;script&gt; tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. In this article, we will see how to sort an array based on user input in AngularJS. Filtering in angular wor
3 min read
Bootstrap 5 Reboot User input
Bootstrap 5 Reboot is a collection of element-specific CSS that changes in a single file, kickstart Bootstrap provides an elegant, consistent, and simple baseline to build upon. Reboot user input is used to indicate the input that is typically entered via the keyboard. Reboot User Input used Tag: &lt;kbd&gt;: This tag is used to define the keyboard
1 min read
How to restrict user character input limit in ReactJS ?
To restrict the user character input limit in React JS we can simply set a max input limit to the input box or we can also monitor the input length and make a custom function to set the restriction. Pre-requisite:NPM &amp; Node.jsReact.jsReact HooksHTML onchange EventApproaches to restrict user character input limit in React JS are: Table of Conten
3 min read
How to highlight text based on user input with React.js ?
One common feature in many applications is the ability to highlight specific portions of text based on user input. In this article, we will explore how to implement text highlighting functionality using React.js. The following approach covers how to highlight text input given by users in ReactJS. It is a simple effect you can add to any ReactJS web
2 min read
How to End setTimeout After User Input ?
To end setTimeout after user input, you can use the clearTimeout function. The clearTimeout() function in JavaScript clears the timeout which has been set by the setTimeout() function before that. Syntax:clearTimeout(name_of_setTimeout);ApproachSet an initial countdown time (e.g., 5 seconds) and a variable for the timeout ID.Use setTimeout to decre
3 min read
How to read user or console input in PHP ?
In PHP, the console is a command-line interface, which is also called interactive shell. We can access it by typing the following command in a terminal: php -a If we type any PHP code in the shell and hit enter, it is executed directly and displays the output or shows the error messages in case of any error. A sample run of a PHP code, that reads i
4 min read
How to show user image along with input field in ReactJS?
We can show the user image along with the input field in React JS. It is like adding an icon image inside the input field. This feature can also be seen on many website login screens. Material UI for React has this component available for us and it is very easy to integrate. We can use the InputAdornment Component in ReactJS using the following app
3 min read
How to take user input in JavaScript?
Interacting with users is the best way to create engaging and dynamic web applications. Taking user input allows your applications to be interactive and responsive. Here we will see the approach to take user input in JavaScript, specifically using the prompt method, which is perfect for beginners. Approach: The "prompt" methodThe prompt method is p
3 min read
Associate user to its upload (post) in Django
Django provides built-in facilities of ForeignKey, and ManytoManyField for associating one model to another model. To associate a user model to a post model, one can use various options. This article revolves around how to associate a user to its post (post model). This tutorial uses the concept of foreign keys in Django and at the end, one will be
5 min read
ReactJS UI Ant Design Form Component
Ant Design Library has this component pre-built, and it is very easy to integrate as well. Form Component is used when the user needs to create an instance or collect information. We can use the following approach in ReactJS to use the Ant Design Form Component. Form Props: colon: It is used to configure the default value of colon for Form.Item.com
5 min read
Which method can be used to get the user's current location in HTML ?
In this article, we will discuss the method to get the user's current location in an HTML document. We will use the Navigator geolocation property that will help us to achieve it. The Navigator geolocation property is used to return a geolocation object by the browser which can be used to locate the user’s position in the HTML document. It is a rea
3 min read
How to close window using JavaScript which is opened by the user with a URL ?
JavaScript does not allow one to close a window opened by the user, using the window.close() method due to security issues. However, we can close a window by using a workaround. The approach to be followed is by opening the current URL using JavaScript so that it could be closed with a script. Syntax:window.close()Approach: The steps below demonstr
2 min read
Principles and Patterns of User Interface Design
User Interface Design is a platform where the effective interaction of the user with the system can be seen. A user more often judges a system by its interface rather than its functionality. An interface that is designed poorly or not leads to improper use of the system by the user. Many users in business systems interact with the systems using a g
3 min read
Difference between &lt;input type='button' /&gt; and &lt;input type='submit' /&gt;
In HTML, &lt;input&gt; elements are widely used to create various form controls. Two common types of &lt;input&gt; elements used for buttons are &lt;input type='button' /&gt; and &lt;input type='submit' /&gt;. While both appear similar at first glance, they serve different purposes and have distinct behaviors when used in web forms, &lt;input type=
3 min read
How to Create User-Friendly Web Design ?
Users are key to the success of any website and therefore should never be neglected. User-friendly in web design simply means designing a website in such a way that makes it easy for users to have access to information that they want on any device without any difficulty. It simply ensures that each and every user of the website must have an easy, e
3 min read