General Date & Time pickers Event Calendar Form components Responsive list Numeric pickers Pickers & dropdowns Layout & navigation Tools Accessibility

Forms

About

The form component adds styling to standard html form elements (textboxes, textareas, selects, checkboxes, radio buttons, submit buttons) giving them a native like look and feel on various platforms.

Initialization

Auto initialization

To auto-initialize the form elements, simply put the mbsc-form attribute on the container element. The form elements inside the container will be automatically intialized when the page is loaded.

<div id="myform" mbsc-form>
    <label>
        Username
        <input id="username" />
    </label>
    <label>
        Password
        <input id="password" type="password" />
    </label>
    <button type="submit">Sign In</button>
</div>

The initialization will use the default options. The defaults can be set in the mobiscroll.settings object, after the Mobiscroll scripts are loaded, but before the page load (document ready) event is fired, in order to have effect on the form initialization.

mobiscroll.settings = {
    theme: 'ios',
    lang: 'de'
};

If the form container is added later to the DOM, e.g. with an Ajax page load, a custom event named mbsc-enhance needs to be triggered in order to initialize the dynamically added content.
When the mbsc-enhance event is triggered on a DOM element, all form elements will be initialized inside all descendant elements with the mbsc-form attribute (including itself).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        var page = document.getElementByID('page');
        page.innerHTML = xhr.responseText;
        page.dispatchEvent(new Event('mbsc-enhance')); 
    }
}
xhr.open('GET', '/myform', true);
xhr.send();
    

Manual Initialization

The form can also initialized manually, just like any other Mobiscroll component.

HTML
<div id="myform">
    <label>
        Username
        <input id="username" />
    </label>
    <label>
        Password
        <input id="password" type="password" />
    </label>
    <button type="submit">Sign In</button>
</div>
Javascript
mobiscroll.form('#myform', {
    theme: 'material'
});

If the form container is added later to the DOM, e.g. with an Ajax page load, call the initialization right after the content is appended in the DOM.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        var page = document.getElementByID('page'),

        page.innerHTML = xhr.responseText;

        mobiscroll.form('#myform', {
            theme: 'mobiscroll'
        });
    }
}
xhr.open('GET', '/myform', true);
xhr.send();

When elements are dynamically added to an already initialized form, call the refresh method to initialize the new elements.

mobiscrollInstance.refresh();

For many more examples - simple and complex use-cases - check out the forms demos for javascript.

Options

Name Type Default value Description
context String, HTMLElement 'body' The DOM element in which the component is appended and positioned (if not inline). Can be a selector string or a DOM element.
theme String undefined

Sets the visual appearance of the component.

If it is 'auto' or undefined, the theme will automatically be chosen based on the platform.

If the theme for the specific platform is not present, it will default to the Mobiscroll theme.

Supplied themes:
  • 'android-holo' - Android 4.x theme
  • 'android-holo-light' - Android 4.x theme (light version)
  • 'ios' - iOS theme
  • 'ios-dark' - iOS dark theme (deprecated)
  • 'material' - Material theme
  • 'material-dark' - Material dark theme (deprecated)
  • 'mobiscroll' - Mobiscroll theme
  • 'mobiscroll-dark' - Mobiscroll dark theme (deprecated)
  • 'wp' - Windows Phone Metro UI theme
  • 'wp-light' - Windows Phone Metro UI theme (light version)
It's possible to create custom themes in css by prefixing any css class used in the forms markup with the theme name and the 'mbsc' prefix, e.g.: .mbsc-my-theme .dwwr { /* My CSS */ }, and set the theme option to 'my-theme'
Make sure that the theme you set is included in the downloaded package.

Events

Name Description
onInit(event, inst) Triggered when the component is initialized.

Parameters

  • event: Object - The event object.
  • inst: Object - The instance object of the forms.

Example

mobiscroll.forms('#mobiscroll', {
    onInit: function (event, inst) {
    }
});

Methods

Name Description
getInst() Returns the object instance.

Returns: Object

  • The object instance.

Example

Methods can be called on an instance. For more details see calling methods
mobiscrollInstance.getInst();
option(options) Sets one or more options for the component.

Parameters

  • options: Object - A map of option-value pairs to set.

Example

Methods can be called on an instance. For more details see calling methods
mobiscrollInstance.option({
    display: 'bottom',
    lang: 'de'
});
refresh() Initialize dynamically added form elements.

Example

Methods can be called on an instance. For more details see calling methods
mobiscrollInstance.refresh();
tap(el, handler) Attaches the handler function to the tap event of element el.

Parameters

  • el: Object - The element with tap event.
  • handler: Function - If the action was initiated with touch event, handler is called on touchend, otherwise on click.

Example

Methods can be called on an instance. For more details see calling methods
mobiscrollInstance.tap('#element', function () { alert("It's a tap!"); });

Localization

Name Type Default value Description
lang String 'en-US' Language of the component. Based on the language string the component loads the language based default settings from the language modules.
Supported languages:
  • Arabic: 'ar'
  • Bulgarian: 'bg'
  • Catalan: 'ca'
  • Czech: 'cs'
  • Chinese: 'zh'
  • Croatian: 'hr'
  • Danish: 'da'
  • Dutch: 'nl'
  • English: 'en' or 'en-US' or undefined
  • English (UK): 'en-UK' or 'en-GB'
  • Farsi: 'fa'
  • German: 'de'
  • Greek: 'el'
  • Spanish: 'es'
  • Finnish: 'fi'
  • French: 'fr'
  • Hebrew: 'he'
  • Hindi: 'hi'
  • Hungarian: 'hu'
  • Italian: 'it'
  • Japanese: 'ja'
  • Korean: 'ko'
  • Lithuanian: 'lt'
  • Norwegian: 'no'
  • Polish: 'pl'
  • Portuguese (Brazilian): 'pt-BR'
  • Portuguese (European): 'pt-PT'
  • Romanian: 'ro'
  • Russian: 'ru'
  • Russian (UA): 'ru-UA'
  • Slovak: 'sk'
  • Serbian: 'sr'
  • Swedish: 'sv'
  • Turkish: 'tr'
  • Vietnamese: 'vi'
offText String 'Off' Text of the switch button when it's turned off, only for Android Holo switch.
onText String 'On' Text of the switch button when it's turned on, only for Android Holo switch.
rtl Boolean false Right to left display.

Validation

The Mobiscroll Forms component does not have built in validation mechanism, but provides error state stylings. Use the mbsc-err css class on the form element's container and the mbsc-err-msg css class on the error message:

Styling an input as invalid
<label class="mbsc-err">
    Username
    <input id="username" />
    <span class="mbsc-err-msg">Username is required.</span>
</label>
    

The above code sample makes a Mobiscroll input to show up as invalid. The text "Username is required" will be shown as the error message.

A functional Example

The following is a simple example on how to validate a login form using a functional approach. The validation requirements for each field are added with standard attributes like required, minlength and the type of the input field.

How it works: on the submit of the form loops over the form fields and validates each field. When a field is invalid, creates the error message element and adds the appropriate css classes to style it. Otherwise, if the field is valid and there is an error message in the markup, then removes it.

A form with two fields: email & password
<form mbsc-form id="myForm">
    <div class="mbsc-form-group">
        <div class="mbsc-form-group-title">Sign In</div>
        <label>
            <input mbsc-input name="email" type="email" placeholder="Email" required>
        </label>
        <label>
            <input mbsc-input name="password" type="password" placeholder="Password" minlength="6" required>
        </label>
    </div>
    <div class="mbsc-form-group mbsc-btn-group-block">
        <button mbsc-button type="submit">Sign in</button>
    </div>
</form>
Example functions for validating form fields
var form = document.getElementById("myForm");

form.noValidate = true; // disable HTML5 validation
form.onsubmit = validateForm; // validate form on submit

// loops through the form elements and validates each field
function validateForm(event) {
    event.preventDefault();
    var formValid = true;
    for (f = 0; f < form.elements.length; f++) {
        var field = form.elements[f],
            error = validateField(field);
        formValid = formValid && !error;
        if (error === null) {
            clearErrorState(field);
        } else {
            addErrorState(field, error);
        }
    }
    return formValid;
}

// checks if a field is valid, and returns the error message
function validateField(field) {
    var name = field.name.charAt(0).toUpperCase() + field.name.slice(1),
        firstError = null,
        errorMap = {
            'tooShort': ' is too short.',
            'typeMismatch': ' is invalid.',
            'valueMissing': ' is required.',
        };
    if (field.validity.valid) {
        return null;
    } else {
        for (var key in field.validity) {
            if (!firstError && key !== 'valid' && field.validity[key]) {
                firstError = key;
            }
        }
        var error = errorMap[firstError] ? errorMap[firstError] : ' is invalid.';
        return name + error;
    }
}

// clears a field of the error state and removes the error message
function clearErrorState(field) {
    var parent = field.parentNode,
        errorMsg = parent.querySelector('.mbsc-err-msg');

    parent.parentNode.classList.remove('mbsc-err');
    if (errorMsg) {
        parent.removeChild(errorMsg);
    }
}

// set the field as invalid and shows the error message
function addErrorState(field, message) {
    var parent = field.parentNode,
        errorMsg = parent.querySelector('.mbsc-err-msg');

    if (!errorMsg) {
        errorMsg = document.createElement('span');
        errorMsg.className = 'mbsc-err-msg';
        parent.appendChild(errorMsg);
    }
    errorMsg.innerHTML = message;
}

Groups

For styling the groups inside the form element you can use the mbsc-form-group, mbsc-form-group-title and mbsc-form-group-inset classes.

<div class="mbsc-form-group">
	<div class="mbsc-form-group-title">Phone</div>
	<label>
		Home
		<input type="tel" class="md-phone" placeholder="Phone" name="phone" value="+12225550127">
	</label>
	<label>
		Work
		<input type="tel" class="md-phone" placeholder="Phone" name="phone" value="+12225550128">
	</label>
</div>
Form group inset
<div class="mbsc-form-group-inset">
	<label>
		<input id="email" type="email" name="Email" placeholder="Email" />
	</label>
	<label>
		<input name="password" type="text" placeholder="Password" data-password-toggle="true" data-icon="none" data-icon-align="right" />
	</label>
</div>