Alternativa de tipos de entrada HTML5 -

PorVitali Malinouski es

Como sabrás, HTML5 ha introducido varios tipos de entrada nuevos: número, fecha, color, rango, etc. La pregunta es: ¿deberías empezar a utilizar estos controles o no? Por mucho que quiera decir “Sí”, creo que todavía no están listos para ningún proyecto de la vida real. La razón principal es la implementación inconsistente por parte de diferentes navegadores.

En el siguiente formulario puede ver algunos de los tipos de entrada HTML5. Dependiendo de su navegador, es posible que vea o no alguna diferencia con respecto a un control de entrada normal.

Entonces, ¿qué deberías utilizar? Puede desarrollar sus propios tipos de entrada o utilizar una biblioteca existente. Probablemente todo el mundo esté familiarizado con el selector de fechas de jQuery u otros complementos de jQuery que vienen al rescate. Sin embargo, todavía no encontró una biblioteca completa que satisfaga todas mis necesidades de entrada, así que decidió crear la mía propia que sería pequeña, consistente y cubriría las siguientes áreas:

  • Entradas numéricas
  • Fecha y hora
  • Listas desplegables
  • Selecciones Múltiples
  • Subir archivo

Trabajó en estos controles durante los últimos años como parte de una gran biblioteca llamada W2UI. Sin embargo, tener en cuenta que una biblioteca independiente con solo controles de entrada podría resultar bastante útil.

Índice de contenidos
  1. Entradas numéricas
    1. Configuración HTML
    2. Creando los campos interactivos
  2. Date and Time
    1. HTML Setup
    2. Creating the Interactive Fields
  3. Drop Down Lists
    1. HTML Setup
    2. Creating the Interactive Fields
  4. Multi-Select Drop Down Lists
    1. HTML Setup
    2. Creating the Interactive Fields
  5. File Upload
    1. JavaScript
    2. Download
    3. About Vitali Malinouski

Entradas numéricas

Las entradas numéricas solo le permitirán escribir números. Ignorarán por completo a todos los demás personajes. Se implementa un soporte completo para teclado. Intente usar las teclas de flecha up/ down, control+ up/ down( command+ up/ downen Mac) para aumentar los números. Cuando se cambie el número, se validará y formateará (si es necesario).

Configuración HTML

!-- Entradas generales --div Entero: /divdiv entrada /divdiv Flotante: /divdiv entrada/divdiv Hexadecimal: /divdiv entrada/divdiv Color: /divdiv entrada/div!-- Formato estadounidense --div Entero: /divdiv valor de entrada ="0" /divdiv Flotante: /divdiv valor de entrada="0" /divdiv Dinero: /divdiv valor de entrada="0" /divdiv Porcentaje: /divdiv valor de entrada="0" /div!-- Formato común de la UE -- div Entero: /divdiv valor de entrada="0" /divdiv Flotante: /divdiv valor de entrada="0" /divdiv Dinero: /divdiv valor de entrada="0" /divdiv Porcentaje: /divdiv valor de entrada="0" /div

Creando los campos interactivos

// General$('#w2int').w2field('int', { autoFormat: false });$('#w2float').w2field('float', { autoFormat: false });$('#w2hex').w2field('hex');$('#w2color').w2field('color');// US Format$('#us-int').w2field('int', { autoFormat: true });$('#us-float').w2field('float', { precision: 3 });$('#us-money').w2field('money', { moneySymbol: '$' });$('#us-percent').w2field('percent', { precision: 1, min: 0, max: 100 });// EU Common Format$('#eu-int').w2field('int', { autoFormat: true, groupSymbol: ' ' });$('#eu-float').w2field('float', { groupSymbol: ' ', precision: 3 });$('#eu-money').w2field('money', { groupSymbol: ' ', currencyPrefix: '', currencySuffix: '€' });$('#eu-percent').w2field('percent', { precision: 1, min: 0, max: 100 });

Second argument is a list of options, that include the following:

options = {min             : null,max             : null,placeholder     : '',autoFormat      : true,currencyPrefix  : '$',currencySuffix  : '',groupSymbol     : ',',arrows          : false,keyboard        : true,precision       : null,silent          : true,prefix          : '',suffix          : ''}

Date and Time

For DATE and TIME types you can use keyboard to increment by a day (or a minute) if you click up/down arrow keys. You can also usectr + up/down (command + up/down on mac) to increment by a month (or an hour).

HTML Setup

!-- US format --div Date: /divdiv input type="us-date" /divdiv From-To: /divdiv input type="us-dateA" span(from 10th to 20th of current month)/span/divdiv Blocked Days: /divdiv input type="us-dateB" span(12,13,14 of current month are blocked)/span/divdiv Date Range: /divdiv input type="us-date1" - input type="us-date2" /divdiv Time: /divdiv input type="us-time" /divdiv From-To: /divdiv input type="us-timeA" span(from 8:00 am to 4:30 pm)/span/div!-- EU common format --div Date: /divdiv input type="eu-date" /divdiv From-To: /divdiv input type="eu-dateA" span(from 10th to 20th of current month)/span/divdiv Blocked Days: /divdiv input type="eu-dateB" span(12,13,14 of current month are blocked)/span/divdiv Date Range: /divdiv input type="eu-date1" - input type="eu-date2" /divdiv Time: /divdiv input type="eu-time" /divdiv From-To: /divdiv input type="eu-timeA" span(from 8:00 am to 4:30 pm)/span/divdiv/div

Creating the Interactive Fields

var month = (new Date()).getMonth() + 1;var year  = (new Date()).getFullYear();// US Format$('input[type=us-date]').w2field('date');$('input[type=us-dateA]').w2field('date', { format: 'm/d/yyyy', start:  month + '/5/' + year, end: month + '/25/' + year });$('input[type=us-dateB]').w2field('date', { format: 'm/d/yyyy', blocked: [ month+'/12/2014',month+'/13/2014',month+'/14/' + year,]});$('input[type=us-date1]').w2field('date', { format: 'm/d/yyyy', end: $('input[type=us-date2]') });$('input[type=us-date2]').w2field('date', { format: 'm/d/yyyy', start: $('input[type=us-date1]') });$('input[type=us-time]').w2field('time',  { format: 'h12' });$('input[type=us-timeA]').w2field('time', { format: 'h12', start: '8:00 am', end: '4:30 pm' });// EU Common Format$('input[type=eu-date]').w2field('date',  { format: 'd.m.yyyy' });$('input[type=eu-dateA]').w2field('date', { format: 'd.m.yyyy', start:  '5.' + month + '.' + year, end: '25.' + month + '.' + year });$('input[type=eu-dateB]').w2field('date', { format: 'd.m.yyyy', blocked: ['12.' + month + '.' + year, '13.' + month + '.' + year, '14.' + month + '.' + year]});$('input[type=eu-date1]').w2field('date', { format: 'd.m.yyyy', end: $('input[type=eu-date2]') });$('input[type=eu-date2]').w2field('date', { format: 'd.m.yyyy', start: $('input[type=eu-date1]') });$('input[type=eu-time]').w2field('time',  { format: 'h24' });$('input[type=eu-timeA]').w2field('time', { format: 'h24', start: '8:00 am', end: '4:30 pm' });

Options for Date

options = {format      : 'm/d/yyyy',  // date formatplaceholder : '',keyboard    : true,silent      : true,start       : '',          // string or jquery objectend         : '',          // string or jquery objectblocked     : {},          // { '4/11/2011': 'yes' }colored     : {}           // { '4/11/2011': 'red:white' }};

Options for Time

options = {format      : 'hh:mi pm',placeholder : '',keyboard    : true,silent      : true,start       : '',end         : ''};

Regular select input is nice, but quite limited. For example, it is hard to use this control on a large set of options. To provide a solution, I have implemented drop down list based on a text input filed but with a dynamic list of options that get filtered as you type.

HTML Setup

div List: /divdiv input type="list" spanCannot type any text, but only items from the list/span /divdiv Combo: /divdiv input type="combo" spanYou can type any text/span /div

Full keyboard support is implemented and it comes with lots of configuration parameters: pulling list of options dynamically from a URL, custom render functions, events, etc.

Creating the Interactive Fields

var people = ['George Washington', 'John Adams', 'Thomas Jefferson', 'James Buchanan', ...];$('input[type=list]').w2field('list', { items: people });$('input[type=combo]').w2field('combo', { items: people });// if you need to get to the selected items, use:// $('#id').data('selected');

Options for List

options = {items       : [],selected    : {},           // selected item as {}placeholder : '',url         : null,         // url to pull data fromcacheMax    : 500,maxWidth    : null,         // max width for input control to growmaxHeight   : 350,          // max height for input control to growmatch       : 'contains',   // ['contains', 'is', 'begins with', 'ends with']silent      : true,onSearch    : null,         // when search needs to be performedonRequest   : null,         // when request is submittedonLoad      : null,         // when data is receivedrender      : null,         // render function for drop down itemshowAll     : false,        // weather to apply filter or not when typingmarkSearch  : true};

Multi-Select Drop Down Lists

Another control I am proud of is multi-select. I cannot image how I used to live without it. It simplified all my UI designswhere I need to select multiple items and now I do not have to use two bulky lists of Available and Selected items.

HTML Setup

div Multi-Select: /divdiv input /divdiv Max 2 Items: /divdiv input /divdiv Custom: /divdiv input /div

Just like the drop down list, it comes with full keyboard support and lots of configuration options (even more then a drop down list). I hope you would enjoy it just as I have over the course of past few years.

Creating the Interactive Fields

var pstyle="padding-right: 3px; color: #828AA7; text-shadow: 1px 1px 3px white;";var people = ['George Washington', 'John Adams', 'Thomas Jefferson', 'James Buchanan', ...];$('#enum').w2field('enum', { items: people,selected: [{ id: 0, text: 'John Adams' }, { id: 0, text: 'Thomas Jefferson' }]});$('#enum-max').w2field('enum', { items: people, max: 2 });$('#enum-custom').w2field('enum', { items: people, onAdd: function (event) {if (Math.random()  0.8) {event.item.bgColor="rgb(255, 232, 232)";event.item.border="1px solid red";}},itemRender: function (item, index, remove) {var html="litoken operator"+ (item.bgColor ? "background-color: '+ item.bgColor + ';' : '') +(item.border ? 'border: '+ item.border + ';' : '') +'" index="'+ index +'"'+remove +'spantoken operator"+ pstyle +'; margin-left: -4px;"/span' + item.text +'/li';return html;},render: function (item, options) {return 'spantoken operator"+ pstyle +'"/span' + item.text;}});// if you need to get to the selected items, use:// $('#id').data('selected');

Options for ENUM

options = {items       : [],selected    : [],placeholder : '',max         : 0,            // max number of selected items, 0 - unlimurl         : null,         // not implementedcacheMax    : 500,maxWidth    : null,         // max width for input control to growmaxHeight   : 350,          // max height for input control to growmatch       : 'contains',   // ['contains', 'is', 'begins with', 'ends with']silent      : true,showAll     : false,        // weather to apply filter or not when typingmarkSearch  : true,render      : null,         // render function for drop down itemitemRender  : null,         // render selected itemitemsHeight : 350,          // max height for the control to growitemMaxWidth: 250,          // max width for a single itemonSearch    : null,         // when search needs to be performedonRequest   : null,         // when request is submittedonLoad      : null,         // when data is receivedonClick     : null,         // when an item is clickedonAdd       : null,         // when an item is addedonRemove    : null,         // when an item is removedonMouseOver : null,         // when an item is mouse overonMouseOut  : null          // when an item is mouse out};

File Upload

And of course, the controls library would not be complete without a file uploader. I have used HTML5 FileReader API(will not work in old browsers, including IE9) to read the file, encode it into base64 and provide to you as a variable thatyou can submit with any AJAX request.

div Attach Files: /divdiv input /div

This approach is new to me, but I kind of like it. It simplifies my file uploads, though has some limitations. The biggest I found so far is the limitation of file size (slow with files over 50MB), however it is comparable to email attachments, which in fact are also base64 encoded into email body.

On a positive side, once you have file encoded into base64, you can use data url API to preview it (if it is an image) or event resize it before submitting to the server with the HTML5 canvas trick.

JavaScript

$('#file').w2field('file', {});// if you need to get to the selected files, use:// $('#file').data('selected');

Options for File

options = {selected     : [],placeholder  : 'Attach files by dragging and dropping or Click to Select',max          : 0,maxSize      : 0,        // max size of all files, 0 - unlimmaxFileSize  : 0,        // max size of a single file, 0 -unlimmaxWidth     : null,     // max width for input control to growmaxHeight    : 350,      // max height for input control to growsilent       : true,itemRender   : null,     // render selected itemitemMaxWidth : 250,      // max width for a single itemitemsHeight  : 350,      // max height for the control to growonClick      : null,     // when an item is clickedonAdd        : null,     // when an item is addedonRemove     : null,     // when an item is removedonMouseOver  : null,     // when an item is mouse overonMouseOut   : null      // when an item is mouse out}

Download

All these controls are part ofW2UI 1.4 (which is in early beta right now). For your convenience, I have put together a small downloadable package with the files you need:

Download w2ui

In order to use it, you will need to include w2ui-fields-1.0.js and w2ui-fields-1.0.css into your app or its minified counterparts. As far as file size goes, it is only 18Kb for the JS file and 6Kb for CSS (minified and gzipped) and has only one dependency – jQuery.

About Vitali Malinouski

Vitali Malinouski is a front-end developer who is passionate about JavaScript UI. He is thinking a lot how to make it easy for people to create user-friendly interfaces and enjoy doing it. He is the author and regular contributor to JavaScript UI library called W2UI.

w2ui.comvitmalinaPosts

Te podría interesar...

Deja una respuesta

Subir