Ski School Scheduler in JavaScript

In this blog post we will create the following timetable that shows the registered ski classes for a ski school week per week:

Ski School Scheduler

We use MindFusion JavaScript Scheduler to create the timetable. We use the BaseForm class to create the custom form that allows us to choose the level of the skier.

This is not possible in the standard appointment form that comes with the scheduling library.

I. General Settings

We need to add a DIV element with an id at the location where we want the timetable to appear on the page. Note that the size of the DIV determines the size of the calendar:

 

MindFusion.Scheduling requires a reference to MindFusion.Scheduling:

<script src="MindFusion.Scheduling.js" type="text/javascript"></script>
<script src="SkiSchoolSchedule.js" type="text/javascript"></script>
<script src="SkiStudentForm.js" type="text/javascript"></script>

We also add a reference to two JavaScript files that will contain the source code for our application: SkiSchoolSchedule and SkiStudentForm. Finally we add a reference to the CSS file that defines the theme used by the timetable – business.css:

<link rel="stylesheet" type="text/css" href="themes/business.css">

The Scheduling library offers a variety of CSS themes, which you can customize or use as a template to create new ones.

II. The Timetable

In the code-behind file we add a mapping to MindFusion.Scheduling namespace and then create the Calendar instance using the id of the DIV element that will render it:

var p = MindFusion.Scheduling;

// create a new instance of the calendar
calendar = new p.Calendar(document.getElementById("calendar"));

// set the view to Timetable, which displays the allotment of resources to distinct hours of a day
calendar.currentView = p.CalendarView.Timetable;

//set the theme to business as referenced calendar.theme = "business";

We also set the currentView property to CalendarView and specify the theme – business as the name of the CSS file that we referenced.

The timetableSettings class exposes a dates property where we add the initial dates that will appear in the view:

//get the current date
var currDay = p.DateTime.today();
calendar.timetableSettings.dates.clear();

/* add dates to the timetable in such manner that always a full week
rom Mo to Su will be visible */
for(var i = 1; i < 8; i++)
{
    calendar.timetableSettings.dates.add(currDay.addDays(-1 * currDay.dayOfWeek + i));
}

We get the current date and add in a cycle all 7 days of the week that contains it. We set the scrollStep property to 7, which indicates the number of days that will appear by initial click on one of the navigation arrows in the header:

// set the number of days to scroll with when a navigation button is clicked
calendar.timetableSettings.scrollStep = 7;

We will also use the startTime and endTime properties to indicate the start and and time of the timetable for each day. Those properties show the time as interval added to the start of the current day, in minutes. Thus a startTime value of 300 means the timetable starts 5 hours (5*60 min.) after midnight of the respective day:

// set the start time to 8:00 AM
calendar.timetableSettings.startTime = 480;
// set the end time to 18:00 PM
calendar.timetableSettings.endTime = 1020;

III. The Custom Form

We don’t want to use the standard form for creating appointments. We will create a custom one, you can see the difference between them at this image:

Ski School Scheduler

The left one is the custom form while to the right you can see the standard New Appointment form for calendar events.

The custom form for creating and editing ski lessons derives from the BaseForm class. Here is its constructor:

var SkiStudentForm = function (calendar, item, type)
{
    p.BaseForm.call(this, calendar, item);

    this._id = "SkiStudentForm";
    this._type = type;
	
    if(type == "new")
        this.headerText = "New Skiing Class";
    else
	this.headerText = "Edit Skiing Class";

    this.levels = [
{ value: 0, text: "beginner" },
{ value: 1, text: "intermediate" },
{ value: 2, text: "advanced" }
]; }

We want each form to have a reference to the Calendar, to the Item that was created and a type. The type is simply a string and we recognize two types: new and edit e.g. whether we create a new class or edit an existing one.

Note that in the constructor we initialize a new variable called levels, which will provide data for the combo box with options for the skiing level of the student.

Then we call the prototype methods of the class and the constructor so we can initialize instances of SkiStudentForm:

SkiStudentForm.prototype = Object.create(p.BaseForm.prototype);
SkiStudentForm.prototype.constructor = SkiStudentForm;

The two methods that are responsible for drawing the contents of a custom BaseForm and its buttons are drawContent and drawButtons

We start with the drawContent method, where we create the first row:

SkiStudentForm.prototype.drawContent = function ()
{
    p.BaseForm.prototype.drawContent.call(this);

    var content = this.content;

    var row = this.row();
    row.className = "header-row";
    row.innerText = "From";
    content.appendChild(row);

    row = this.row();
    row.className = "data-row";
    row.innerHTML = this.item.startTime.toString("dddd, MMMM d,  HH:00", this.formatInfo);
    content.appendChild(row);
    ........................
}

We call the prototype of the drawContent method and we add a new row element. The row is an empty DIV. Then we add another row, this one contains a string. The string represents the start time of the Item .

We create the combo box using the createDropDownList method. Before we create the combo box we add a new DIV with the label. Then we add another DIV and the dropDownList element to it:

// create a drop-down list for status
row = this.row();
row.className = "header-row";
row.innerHTML = "Level";
content.appendChild(row);

var control = this.createDropDownList({ id: "level", items: this.levels, initValue: this.item.tag, addEmptyValue: false });
control.element.style.width = "200px";
this.addControl(control);

row = this.row();
row.className = "input-row";
row.appendChild(control.element);
content.appendChild(row);

The drawButtons method that we implement overrides the buttons of the BaseForm with new ones, styled as we want. Here the code for the Save button:

// override BaseForm's drawButtons method to create form buttons
SkiStudentForm.prototype.drawButtons = function ()
{
    var thisObj = this;

    var btnSave = this.createButton(
{ id: "btnSave", text: "✔", events: {
"click": function click(e) { return thisObj.onSaveButtonClick(e); } } }); btnSave.element.className = "form-button-save";

We use the createButton method to create the button, give it an id and assign a text to it. We also indicate the the click event will be handled by an implementation of the default onSaveButtonClick event for BaseForm

The Cancel button is the same, just the CSS styling for it is different. Both buttons use custom CSS class, which are assigned to them through the className property of HTML Dom elements. Here is the code for the appearance of the two buttons:

.form-buttons
{
	color: #fff;
	font-size: x-large;
	text-align: center;
	margin-top: 20px !important;
}
.form-button-save
{
	width: 80%;
	padding: 10px;
	background-color: #31bd41 !important;
}
.form-button-cancel
{
	width: 20%;
	padding: 10px;
	background-color: #ce0000 !important;
}

We create and render an instance of the form with the following lines of code:

var form = new SkiStudentForm(sender, item, "new");
form.showForm();

Here we create the form from an event handler for the Calendar class – we will look at that in the next section.

IV. Events

We show the student appointment form when a selection of cells is make. In order to do this we handle the selectionEnd method of the Calendar class:

// handle the selectionEnd event to show the custom form for item creation
calendar.selectionEnd.addEventListener(handleSelectionEnd);
function handleSelectionEnd(sender, args)
{	
    // we create a new item with the selected start and end time
    var item = new p.Item();
    item.startTime = args.startTime;
    item.endTime = args.endTime;	
    item.tag = 0;	

    // create and show the custom form
    var form = new SkiStudentForm(sender, item, "new");
    form.showForm();
}

We create a new Item and we set its startTime and endTime to the start and end of the selected cell range. Then we use the current Calendar, which is provided as a sender, the newly created Item and “new” as type to create an instance of the SkiStudentForm and render it.

What shall we do if we want to use the custom form to edin an existing appointment? We will handle the itemDoubleClick event of the Calendar and show the SkiStudentForm. In this case we will get the Item that we want to edit and provide it as a parameter to the SkiStudentForm instance. We also change the type to be “edit”:

function handleItemDoubleClick(sender, args)
{	
    // show the custom form with data from the clicked item
    var form = new SkiStudentForm(sender, args.item, "edit");
    form.showForm();
}

These were the most important parts of the ski school scheduler application. The application has a few more, which we did not mention here but you can check them in code. The complete code, together with the themes and libraries used is available at:

Download the Ski School Scheduler Application

You can post technical questions, comments and recommendations about MindFusion Scheduling for JavaScript at the library online forum.

About Scheduling for JavaScript: MindFusion Js Scheduler is the right solution for all applications that need to render interactive timetables, rich event calendars, lists with appointments or resources. Fully responsive, highly customizable and easy to integrate, you can quickly program the JavaScript scheduling library according to your needs. The library supports a variety of export options, styling through themes, 6 calendar views and much more. Find out more at https://mindfusion.eu/javascript-scheduler.html

Organization Services Chart with the JavaScript Diagram Library

In this blog post we will use MindFusion JavaScript Diagram library to build an application that allows the users to create a diagram with nodes that hold icons and text. We have used this online diagram application to build an infogram for the services portfolio of an imaginary company. However, you can replace the icons and use it as a tool to build diagrams of whatever domain is of interest to you.

In the sample diagram we use SVG images from Google’s material design icons set. You can download them from https://github.com/google/material-design-icons.


Our sample application uses a Diagram and a NodeListView controls – both of them part of JsDiagram.

I. General Settings

We need to add two HTML Canvas elements to the web page where the sample application will be. One is for the NodeListView and the other is for the Diagram

<div style="width: 70px; height: 100%; overflow-y: auto; overflow-x: hidden; position: absolute; top: 5px; left: 0px; right: 0px; bottom: 0px;">
    <canvas id="nodeList" width="200"></canvas>
</div>
...........................
<div style="position: absolute; left: 70px; top: 5px; right: 0px; bottom: 0px; overflow: auto;">
    <canvas id="diagram" width="2100" height="2100">
        This page requires a browser that supports HTML 5 Canvas element.
    </canvas>
</div>

We place the two Canvas elements using CSS next to each other. The NodeListView is in a long and narrow Canvas and next to it is the Diagram Canvas, which has a big size of 211 pixels. It is important that we provide the two Canvases with id-s: we will refer to them later in the JavaScript code using these id-s.

Then we add references to the two JavaScript files that we use from the Diagram library – MindFusion.Diagramming and MindFusion.Common:

<script src="Scripts/MindFusion.Common.js" type="text/javascript"></script>
<script src="Scripts/MindFusion.Diagramming.js" type="text/javascript"></script>
<script src="OrgInfoDiagram.js" type="text/javascript"></script>

The last JavaScript file that we reference is OrgInfoDiagram and there we keep the code for our application.

II. The Diagram

We create the Diagram object by using the reference to the Canvas that will render it:

// create a Diagram component that wraps the "diagram" canvas
diagram = Diagram.create(document.getElementById("diagram"));

Then we use an instance of the Style class to create a style that will determine how newly created –DiagramNode -s are styled:

//styling
var shapeNodeStyle = new Style();
shapeNodeStyle.setBrush({ type: 'SolidBrush', color: '#e0e9e9' });
shapeNodeStyle.setStroke("Orange");
shapeNodeStyle.setFontName("Verdana");
shapeNodeStyle.setFontSize(9);   
shapeNodeStyle.setNodeEffects([new GlassEffect()]);

The Style instance applies GlassEffect on the new nodes and places a thick orange border around them. We also allow users to edit diagram nodes by calling setAllowInplaceEdit .

diagram.setStyle(shapeNodeStyle);
diagram.setAllowInplaceEdit(true);

III. The NodeListView

The NodeListView control can hold both text and image nodes. We create it the same way we created the Diagram : by using the id of its Canvas element:

// create a NodeListView component that wraps the "nodeList" canvas
var nodeList = MindFusion.Diagramming.NodeListView.create(document.getElementById("nodeList"));
nodeList.setTargetView(document.getElementById("diagram"));
nodeList.setIconSize(new Size(36, 36));
nodeList.setDefaultNodeSize (new Size(18, 18));

It is important that we set the target of the NodeListView – this is the Canvas, where the newly created DiagramNode will be rendered. We also set the size of the icons in the NodeListView and the size that newly created nodes will have. For this we use the setIconSize and setDefaultNodeSize methods respectively.

We create the nodes for the NodeListView in a special method called initNodeList:

function initNodeList(nodeList, diagram)
{
    var node = new ShapeNode(diagram);
    node.setText("text");
    node.setShape("Ellipse");
    node.setPen("Gray");		
    node.setBrush("White");
    node.setBounds(new Rect(0, 0, 48, 48));
    node.setEnableStyledText(true);
    node.setFont(new Font("sans-serif", 12, true));
    node.setStrokeThickness(2);
    nodeList.addNode(node);
    .......................................

The first ShapeNode that we create is a standard text node with the difference that we enable styled text for it: that means the user can enter bold, italic or underline text using the standard HTML tags <b>, <i>, <u>. We specify this with the method setEnableStyledText . We also add the node to the NodeListView that we have provided to the method.

In order to create nodes with SVG images, we need to create instances of the SvgNode class:

// add some nodes to the NodeListView
var svgImages = ["call", "reader", "computer", "data", "car", "text", "music", "movie", "nature", "calendar", "chart", "router",  "account", "alarm", "announcement", "book", "calls", "copyright", "event", "grade", "group_work", "info", "key", "list", "payment", "phone", "shop", "sign", "textsms", "theaters", "work"];
for (var i = 1; i <= svgImages.length; ++i)
{
    node = new MindFusion.Diagramming.SvgNode(new Rect(0, i * 48, 48, 48));
    node.setTransparent(true);
var content = new SvgContent(); content.parse(svgImages[i] + ".svg"); node.setContent(content);
nodeList.addNode(node); }

We have copied the desired icons in the directory of the application and we have listed their names in a list. Then we cycle through all members of the list and create instances of the SvgNode class. We set their background to be transparent and we render the images thanks to the SvgContent class. Finally we also add the newly created SvgNode -s to the node list.

We call the initNodeList method providing the nodeList and diagram instances:

initNodeList(nodeList, diagram);

IV. Events

Though the code so far is enough to provide the desired functionality of our application, we want to customize the newly created diagram nodes and links. This can be achieved through events. We handle two of them onNodeCreated and LinkCreated.

diagram.addEventListener(Events.nodeCreated, onNodeCreated);
diagram.addEventListener(Events.linkCreated, onLinkCreated);

In the NodeCreated event handler we get the ShapeNode that is being created and make its shape to a round one with the setShape method. We assign to it a thick orange border and add some padding to the images – in case it is an SvgNode:

function onNodeCreated(sender, args)
{
    var node = args.getNode();
    node.setTransparent(false);
    node.setShape("Ellipse");
    node.setStroke("orange");
    node.setStrokeThickness(3);
    node.setFont(new Font("sans-serif", 4));
    node.setImagePadding(new Thickness(1.5, 1.5, 1.5, 1.5));
}

The linkCreated event handler applies some styling, but to newly created DiagramLink instances”

function onLinkCreated(sender, e)
{
    var link = e.getLink();
    link.setBaseShape(null);
    link.setHeadShape(null);
    link.setStrokeThickness(3.0);
}

We remove the default base and head shapes of the diagram links and leave the connectors to be just straight lines. We also draw them with a thick orange pen.

And these were the last lines of code that we had to add to make the application complete. You can download the source code, together with all all Diagramming libraries used from this link:

Download Organigram Application in JavaScript Source Code

You can use MindFusion Diagramming for JavaScript forum to post your questions, comments and recommendations about this sample or the Js Diagram library.

About Diagramming for JavaScript: This native JavaScript library provides developers with the ability to create and customize any type of diagram, decision tree, flowchart, class hierarchy, graph, genealogy tree and more. The control offers rich event set, numerous customization options, animations, graph operations, styling and themes. You have more than 100 predefined nodes, table nodes and more than 15 automatic layout algorithms. Learn more about Diagramming for JavaScript at https://mindfusion.eu/javascript-diagram.html.

Different-size Icons in the Js Diagram NodeListView

In this blog post we will learn how to add a NodeListView control to a Diagram and how to set its ShapeNode -s to a different size. When ShapeNode -s are dragged from the NodeListView the instances that will be created are proprtional in size to the size of the ShapeNode that was dragged. Here is a screenshot of the final application:

I. General Settings

We create an HTML page and add to it references to the MindFusion JavaScript files that represent the diagramming library:

<script src="MindFusion.Common.js" type="text/javascript"></script>
<script src="MindFusion.Diagramming.js" type="text/javascript"></script>
<script src="Controls.js" type="text/javascript"></script>

The last reference is to the Controls JavaScript file, where the code for the application is located.

Then we create two Canvas-es: one is for the NodeListView and the other is for the Diagram The NodeListView component is bound to the canvas element below:

<div style="width: 200px; height: 100%; overflow-y: auto; overflow-x: hidden; position: absolute; top: 201px; left: 0px; right: 0px; bottom: 0px;">
    <canvas id="nodeList" width="200"></canvas>
</div>
......
<!-- The Diagram component is bound to the canvas element below -->
<div style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: auto;"> <canvas id="diagram" width="2100" height="2100">
This page requires a browser that supports HTML 5 Canvas element.
</canvas>
</div>

Both the Diagram and NodeListView controls require Canvas elements to render themselves onto.

II. Initializing the Controls

We create the Diagram using the id that we’ve provided to its Canvas in the web page:

// create a Diagram component that wraps the "diagram" canvas
diagram = Diagram.create(document.getElementById("diagram"));
diagram.setBounds(new MindFusion.Drawing.Rect(0, 0, 500, 500));

We set a bigger size to the diagram in order to make it fill the web page.

We create the NodeListView instance the same way we created the diagram:

// create a NodeListView component that wraps the "nodeList" canvas
var nodeList = MindFusion.Diagramming.NodeListView.create(document.getElementById("nodeList"));
nodeList.setTargetView(document.getElementById("diagram"));

Now we need to add the settings that will make the ShapeNode -s different in size when rendered onto the list:

nodeList.setIconSize(null);

The setIconSize method is used to specify the default size of nodes in the NodeListView When we set the size to null, the control draws each node in the NodeListView with the size that was assigned to it:

function initNodeList(nodeList, diagram)
{
    // add some nodes to the NodeListView
    var shapes = ["Actor", "RoundRect", "Triangle", "Decision"];
    for (var i = 0; i < shapes.length; ++i)
    {
        var node = new MindFusion.Diagramming.ShapeNode(diagram);
        node.setText(shapes[i]);
        node.setShape(shapes[i]);
        node.setBounds(new MindFusion.Drawing.Rect(0, 0, (i+1)*10, (i+1)*10));
        nodeList.addNode(node, shapes[i]);
    }
}

Here we increase the size of wach ShapeNode with 10 points on each itereation. This makes the icons with various size but does not create them with different size when dropped on the diagram. In order to do this we must set:

nodeList.setDefaultNodeSize (null);

setDefaultNodeSize specifies the size of those nodes that are created when a ShapeNode is dropped on the Diagram area. By setting this size to null we tell the control to read the size of the new ShapeNode from the instance in the NodeListView control.

With that our sample is ready. You can download the source code from this link:

JavaScript NodeListView with Various Size Nodes: Download Sample

About Diagramming for JavaScript: This native JavaScript library provides developers with the ability to create and customize any type of diagram, decision tree, flowchart, class hierarchy, graph, genealogy tree and more. The control offers rich event set, numerous customization options, animations, graph operations, styling and themes. You have more than 100 predefined nodes, table nodes and more than 15 automatic layout algorithms. Learn more about Diagramming for JavaScript at https://mindfusion.eu/javascript-diagram.html.

JavaScript Diagram with Chart Nodes

In this blog post we will create DiagramNode instances that render a chart. The charts get resized according to the size of the node. We will use two MindFusion libraries for JavaScript – Charting and Diagramming. You can run the sample online from this link:

I. Project Setup

We will use a web page that will hold the HTML Canvas element that we need in order to render the diagram:

<div style="width: 100%; height: 100%; overflow: scroll;">
    <canvas id="diagram" width="2100" height="2100" style="background:#f0f0f0;">
        This page requires a browser that supports HTML 5 Canvas element.
    </canvas>
</div>

We give the diagram’s Canavs big width and height and we also provide an id. The id is important because we will need to access the Canvas from code.

We add the scripts that we need in order to use the Charting and Diagramming libraries:

<script src="Scripts/MindFusion.Common.js" type="text/javascript"></script>
<script src="Scripts/MindFusion.Diagramming.js" type="text/javascript"></script>
<script src="Scripts/MindFusion.Charting.js" type="text/javascript"></script>

We add the references at the end of the web page, just before the closing BODY tag. We also need to add a reference to a JavaScript file that will hold the code for our sample. We name it “PieNode.js”.

II. The Diagram

In the code-behind file we create a diagram instance. We use the DOMContentLoaded event to initialize our diagram:

document.addEventListener("DOMContentLoaded", function ()
{
// create a Diagram component that wraps the "diagram" canvas
diagram = MindFusion.Diagramming.Diagram.create(document.getElementById("diagram"));
diagram.setBehavior(MindFusion.Diagramming.Behavior.LinkShapes);
diagram.setLinkHeadShapeSize(2);
diagram.setBounds(new Rect(0, 0, 2000, 2000));

// draw a pie when the user creates a node
diagram.addEventListener(Events.nodeCreated, onNodeCreated);

});

The Behavior enumeration lists various modes of behavior for the diagram. We choose Behavior.LinkShapes, which creates nodes, when the mouse is dragged
over an empty area and connects the nodes if the mouse is dragged from an existing node. We set tbe bounds of the diagram to a big Rect which guarantees that the user can draw nodes anywhere on the visible area. When the user draws towards the edge of the browser, the diagram control expands automatically.

Finally, we add an event handler for the nodeCreated event.

//nodeCreated event handler
function onNodeCreated(sender, args)
{
	var node = args.getNode();
	
	var nBounds = node.getBounds ();
	var topLeftCoord = diagram.docToClient(nBounds.topLeft());
	var bottomRightCoord = diagram.docToClient(nBounds.bottomRight());
	.......................................................
}

At first we get the node that was created. Then we need to get its actual size, for which we use the docToClient method that converts between diagram and browser measure units. We get the two coordinates of the node’s bounding rectangle.

We create then a Canvas, which takes the size of the node’s rectangle:

............................................
.....................................................
var pieChartCanvas = document.createElement('canvas');
pieChartCanvas.width = bottomRightCoord.x - topLeftCoord.x;
pieChartCanvas.height = bottomRightCoord.y - topLeftCoord.y;

We then add this temp canvas to the body of the web page and call a method “createPie” where we draw the pie chart. Once the chart is drawn we get the URL of the image and set is to the node with the setImageLocation method. We remove the Canvas from the tree with the elements because we want to use for the next node.

//create a temporary Canvas for the pie chart
//to draw itself upon
document.body.appendChild(pieChartCanvas);
createPie(pieChartCanvas);
var pieImageLocation = pieChartCanvas.toDataURL();
node.setImageLocation(pieImageLocation);
document.body.removeChild(pieChartCanvas);

III. The Chart

We create a pie chart in the Canvas provided to the createPie method:

//draw a pie chart on the provided canvas
function createPie(pieChartCanvas)
{
	var pieChart = new Controls.PieChart(pieChartCanvas);
	pieChart.startAngle = 45;			
	pieChart.showLegend = false;
	pieChart.title = "Sales";
	pieChart.titleMargin = new Charting.Margins(0, 10, 0, 0);
	pieChart.chartPadding = 3;
...........................

We set some appearance properties to make the chart look the way we want – change the start angle of the pie, add a title and title margin, hide the legend. Then we create a PieSeries which holds the data and the labels of the pie. We assign the PieSeries to the series property of the pie chart:

// create sample data
var values = new Collections.List([20.00, 30.00, 15.00, 40.00]);
pieChart.series = new Charting.PieSeries(
	values,
	new Collections.List(["20", "30", "15", "40"]),
null);

We style the chart with an instance of the PerElementSeriesStyle class, which colors all elements of a Series with the consequtive Brush and stroke from its brushes and strokes collections. Then we adjust the dataLabelsFontSize to match the size of the canvas. We make the labels be drawn with a white brush using the dataLabelsBrush property. Finally we call draw to render the pie.

var brushes = new Collections.List(
		[
			new Drawing.Brush("#0455BF"),
			new Drawing.Brush("#033E8C"),
			new Drawing.Brush("#F24405"),
			new Drawing.Brush("#F21905")
		]);

	var seriesBrushes = new Collections.List();
	seriesBrushes.add(brushes);

	var strokes = new Collections.List(
		[
			new Drawing.Brush("#c0c0c0")
		]);

	var seriesStrokes = new Collections.List();
	seriesStrokes.add(strokes);

	pieChart.plot.seriesStyle = new Charting.PerElementSeriesStyle(seriesBrushes, seriesStrokes);
	pieChart.theme.highlightStroke = new Drawing.Brush("#000063");
	pieChart.theme.dataLabelsFontSize = pieChartCanvas.height/20;
	pieChart.theme.dataLabelsBrush = new Drawing.Brush("#FFFFFF");

	pieChart.draw();

And with that the sample is ready. You can download the source code together with all MindFusion JavaScript libraries used from:

https://mindfusion.eu/samples/javascript/diagram/PieNodes.zip

About Diagramming for JavaScript: This native JavaScript library provides developers with the ability to create and customize any type of diagram, decision tree, flowchart, class hierarchy, graph, genealogy tree and more. The control offers rich event set, numerous customization options, animations, graph operations, styling and themes. You have more than 100 predefined nodes, table nodes and more than 15 automatic layout algorithms. Learn more about Diagramming for JavaScript at https://mindfusion.eu/javascript-diagram.html.

About Charting for JavaScript: MindFusion library for interactive charts and gauges. It supports all common chart types including 3D bar charts. Charts can have a grid, a legend, unlimited number of axes and series. Scroll, zoom and pan are supported out of the box. You can easily create your own chart series by implementing the Series interface.
The gauges library is part of Charting for JavaScript. It supports oval and linear gauge with several types of labels and ticks. Various samples show you how the implement the gauges to create and customize all popular gauge types: car dashboard, clock, thermometer, compass etc. Learn more about Charting and Gauges for JavaScript at https://mindfusion.eu/javascript-chart.html.

Multi-tabs Form in JavaScript with Validation

In this blog post we will create a form that spans over several tabs. Each tab contains input fields for a specific type of information. There are placeholders and restrictions for each input field. If the provided data is not correct we display a guiding message and select the first tab that has wrong data. All incorrect fields are outlined with red.

I. General Settings

We will use two files for our form – one is a web page and the other a JavaScript file that will hold all JavaScript code for the sample. They both are names TabForm.

In the web page we add references to the css file that holds the theme we’ve chosen:

<link rel="stylesheet" type="text/css" href="themes/light.css">

This is the CSS for the light theme of the MindFusion JavaScript UI controls. There are various themes provided out-of-the-box with the library and you can choose another one.

Then, at the bottom of the web page, before the closing BODY tag we add references to the three JavaScript files that we want to use:

<div style="position: absolute; top: 0px; left: 0; right: 0; bottom: 0;">
    <div id="host">
    </div>
</div>

The first two of them point to the libraries of the UI controls: MindFusion.Common and MindFusion.UI. The other is a reference to the JS code-behind file.

In order to render the TabControl we need a DIV element. So, we create one and give it an id – that is important:

We also add a paragraph with an id and red stroke – it will render text, that describes the error fields and the validation message for each one – if the user has provided wrong data.

II. Creating the Tab Control and the Tab Pages

In the code-behind file we first add mappings to the two namespaces we want to use:

var ui = MindFusion.UI;
var d = MindFusion.Drawing

Then we create an instance of the TabControl in code this way:

// Create a new TabControl.
var host = new ui.TabControl(document.getElementById("host"));
host.width = new ui.Unit(70, ui.UnitType.Percent);
host.height = new ui.Unit(70, ui.UnitType.Percent);
host.theme = "light";

We use the id of the DIV element in the constructor of the TabControl Then we use the theme property to refer to the theme that we want to use. The value of the theme property should be the same as the name of the CSS ile that we referenced in the web page. It can point to a custom theme that you have created as long as the names of the file and the property value match.

We create the first TabPage as an instance of the TabPage class:

// Create four templated tab pages and add them to the host's tabs collection.
var tab1 = new ui.TabPage("Owner Details");
// The HTML of the specified page will be set as the innerHTML of a scrollable div inside the tab content element.
tab1.templateUrl = "page1.html";
host.tabs.add(tab1);

We provide the string that will render in the title of the TabPage in the constructor. Then we set the content that the TabPage will have as a url to the web page that contains it e.g. the TabPage loads a content from a page specified with templateUrl Here is the code for the first page:


In terms of HTML, we have provided each input element with an id, a placeholder value and the necessary restrictions that will validate its content. We strictly use and follow the Validation API of JavaScript, which you can check here: https://www.w3schools.com/js/js_validation_api.asp and here https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation.

III. Data Submission and Validation

On the last tab of the form, we have placed a submit button:

We wire the event handler of the click action for this button in the contentLoad event of the fourth tab, where the button is:

tab4.contentLoad.addEventListener(tabLoad);
..........................
..........................
function tabLoad(sender, args) {

    let current_datetime = new Date();
    let formatted_date = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate();
    sender.element.querySelector("#start").value = formatted_date;
    sender.element.querySelector("#submit").addEventListener("click", function () {
    submitData(sender);
    });
}

In the event handler we get the current date and format it the way the default DateTime picker HTML control expects to get it. We get each input control through its id and the querySelector of the HTML Document object. The sender in this case is the fourth tab or tab4.

The method that validates the content is submitData:

function submitData(sender) {
    var txt = "";

    var inputObj = tab4.element.querySelector("#start");

    if (!inputObj.checkValidity()) {
        txt += inputObj.name + ": ";
        txt += inputObj.validationMessage + "
";
        inputObj.style["border-color"] = "red";
        host.selectedItem = tab4;
        dataIsCorrect = false;
    } else
        inputObj.style["border-color"] = "gray";
        ....................................

We use querySelector once again to get the input fields on each page one by one. For each one we see if the validity check has failed. If yes, we outline this field in red and append the validation message to a text variable.

We walk through all tabs and all input fields in this same manner and in reverse order. Our aim is that the first tab with error gets selected, even if there are errors in fields further in the form.

Note that if the field is OK we set its border to the default color. This way we reset the appearance of fields that were previously wrong but the user has corrected.

Finally, we assign the text to the content of the paragraph that renders text in red:

...............................
document.getElementById("error").innerHTML = txt;  

    if (txt.length === 0)
        confirmData();

If no errors have been detected – that means the error text is an empty string – we submit the data. The data submission is handled by the confirmData method:

function confirmData() {

    //first tab
    tab1.element.querySelector("#fname").value = "";
    tab1.element.querySelector("#lname").value = "";
    tab1.element.querySelector("#citizen_id").value = "";
    ........................................
    ........................................
     //fourth tab
    tab4.element.querySelector("#duration").value = "";
    let current_datetime = new Date();
    let formatted_date = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate();
    tab4.element.querySelector("#start").value = formatted_date;

    ui.Dialogs.showInfoDialog("Confirmation", "Your info has been submitted!", null, host.element, host.theme);

}

We reset the values of all input fields and we show an instance of MindFusion InfoDialog to inform the user that their data has been successfully collected.

You can download the source code of the sample and all MindFusion themes and libraries used from this link:

https://mindfusion.eu/samples/javascript/ui/TabForm.zip

You can ask technical question about MindFusion JavaScript developer tools at the online forum at https://mindfusion.eu/Forum/YaBB.pl.

About MindFusion JavaScript UI Tools: MindFusion UI libraries are a set of smart, easy to use and customize JavaScript UI components. Each control boasts an intuitive API, detailed documentation and various samples that demonstrate its use. The rich feature set, multiple appearance options and numerous events make the UI controls powerful tools that greatly facilitate the programmers when building interactive JavaScript applications. MindFusion UI for JavaScript is part of MindFusion JavaScript Pack. You can read details at https://mindfusion.eu/javascript-pack.html.