Forms related code snippets

Here are some <form> related code snippets.

Date picker

(before implementing it in a working environment, please read the note about the const statement compatibility)

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>DatePicker Example - MDN</title>
<script type="text/javascript">

/*\
|*|
|*|  DatePicker Example MDNDeveloper Network
|*|
|*|  https://developer.mozilla.org/docs/Code_snippets/Forms
|*|  https://developer.mozilla.org/User:fusionchess
|*|
|*|  This snippet is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
\*/

(function () {

  function DatePicker (oTarget) {

    const

      oTable = document.createElement("table"), oHRow = document.createElement("tr"),
      oTHead = document.createElement("thead"), oCapt = document.createElement("caption"),
      oDecrYear = document.createElement("span"), oIncrYear = document.createElement("span"),
      oDecrMonth = document.createElement("span"), oIncrMonth = document.createElement("span");

    var

      nId = aInstances.length, oTH;

    this.target = oTarget;
    this.display = document.createElement("span");
    this.current = new Date();
    this.container = oTable;
    this.display.className = sPrefs + "-current-month";
    this.id = nId;
    oTable.className = sPrefs + "-calendar";
    oTable.id = sPrefs + "-cal-" + nId;
    oDecrYear.className = sPrefs + "-decrease-year";
    oDecrMonth.className = sPrefs + "-decrease-month";
    oIncrMonth.className = sPrefs + "-increase-month";
    oIncrYear.className = sPrefs + "-increase-year";
    oDecrYear.innerHTML = "\u00AB"; /* &laquo; */
    oDecrMonth.innerHTML = "\u003C"; /* &lt; */
    oIncrMonth.innerHTML = "\u003E"; /* &gt; */
    oIncrYear.innerHTML = "\u00BB"; /* &raquo; */
    oDecrYear.id = sPrefs + "-decr-year-" + nId;
    oDecrMonth.id = sPrefs + "-decr-month-" + nId;
    oIncrMonth.id = sPrefs + "-incr-month-" + nId;
    oIncrYear.id = sPrefs + "-incr-year-" + nId;
    oDecrYear.onmousedown = oIncrYear.onmousedown = oDecrMonth.onmousedown = oIncrMonth.onmousedown = onHeadClick;

    for (var nThId = 0; nThId < 7; nThId++) {
      oTH = document.createElement("th");
      oTH.innerHTML = sDays[nThId];
      oHRow.appendChild(oTH);
    }

    oTHead.appendChild(oHRow);
    oCapt.appendChild(oDecrYear); oCapt.appendChild(oDecrMonth); oCapt.appendChild(oIncrYear); oCapt.appendChild(oIncrMonth);
    oCapt.appendChild(this.display); this.container.appendChild(oCapt); this.container.appendChild(oTHead);

    this.current.setDate(1);
    this.writeDays();

    oTarget.onclick = function () {
      if (oTable.parentNode) {
        oTable.parentNode.removeChild(oTable);
        return;
      }
      oTable.style.zIndex = nZIndex++;
      oTable.style.position = "absolute";
      oTable.style.left = oTarget.offsetLeft + "px";
      oTable.style.top = (oTarget.offsetTop + oTarget.offsetHeight) + "px";
      oTarget.parentNode.insertBefore(oTable, oTarget);
    };

    aInstances.push(this);

  }

  DatePicker.prototype.writeDays = function () {

    const

      nEndBlanks = (this.current.getDay() + bZeroIsMonday * 6) % 7,
      nEnd = aMonthLengths[this.current.getMonth()] + nEndBlanks,
      nTotal = nEnd + ((7 - nEnd % 7) % 7);

    var

      oTD, oTR;

    if (this.oTBody) { this.container.removeChild(this.oTBody); }

    this.oTBody = document.createElement("tbody");

    for (var nDay, oDay, nIter = 0; nIter < nTotal; nIter++) {
      if (nIter % 7 === 0) {
        oTR = document.createElement("tr");
        this.oTBody.appendChild(oTR);
      }
      nDay = nIter - nEndBlanks + 1;
      oTD = document.createElement("td");
      if (nIter + 1 > nEndBlanks && nIter < nEnd) {
        oTD.className = sPrefs + "-active-cell";
        oTD.id = sPrefs + "-day-" + this.id + "-" + nDay;
        oTD.onclick = onDayClick;
        oTD.appendChild(document.createTextNode(nDay));
      } else {
        oTD.className = sPrefs + "-empty-cell";
      }
      oTR.appendChild(oTD);
    }

    this.display.innerHTML = sMonthsNames[this.current.getMonth()] + " " + this.current.getFullYear();
    this.container.appendChild(this.oTBody);

  };

  function onDocClick (oPssEvt) {
    const oEvt = oPssEvt || /* IE */ window.event;
    var bOutside = true;
    for (var oNode = oEvt.target || /* IE */ oEvt.srcElement; oNode; oNode = oNode.parentNode) {
      if (oNode.className === sPrefs + "-calendar" || oNode.className === sDPClass) {
        bOutside = false;
        break;
      }
    }
    if (bOutside) { return; }
    aInstances[oNode.id.replace(rBgnNaN, "")].container.style.zIndex = nZIndex++;
  }

  function onHeadClick () {
    const bIsMonth = rMonth.test(this.id), nDelta = rDecrease.test(this.id) ? -1 : 1, oThisCal = aInstances[this.id.replace(rBgnNaN, "")];
    oThisCal.current[bIsMonth ? "setMonth" : "setYear"](oThisCal.current[bIsMonth ? "getMonth" : "getFullYear"]() + nDelta);
    oThisCal.writeDays();
    return false;
  }

  function onDayClick () {
    const oThisCal = aInstances[this.id.replace(rBgnANDEnd, "")];
    oThisCal.target.value = (this.innerHTML / 100).toFixed(2).substr(-2) + "\/" + (oThisCal.current.getMonth() + 1) + "\/" + oThisCal.current.getFullYear();
    oThisCal.container.parentNode.removeChild(oThisCal.container);
    return false;
  }

  function buildCalendars () {
    const aFields = document.getElementsByClassName(sDPClass), nLen = aFields.length;
    for (var nItem = 0; nItem < nLen; new DatePicker(aFields[nItem++]));
  }

  const

    /* customizable by user */
    sPrefs = "zdp";
    sDPClass = "date-picker",
    sMonthsNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    sDays = ["M", "T", "W", "T", "F", "S", "S"],
    bZeroIsMonday = true,

    /* internal usage */
    aInstances = [],
    aMonthLengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
    rBgnNaN = /^\D+/, rBgnANDEnd = /^\D+|\D+\d+$/g, rMonth = /\-month\-/, rDecrease = /\-decr\-/;

  var

    /* customizable by user */
    nZIndex = 1000;

  window.addEventListener ? addEventListener("load", buildCalendars, false) : window.attachEvent ? attachEvent("onload", buildCalendars) : (onload = buildCalendars);

  document.addEventListener ? document.addEventListener("mousedown", onDocClick, false) : document.attachEvent ? document.attachEvent("onmousedown", onDocClick) : (document.onmousedown = onDocClick);

})();

</script>
<style type="text/css">
table.zdp-calendar {
  border: 1px solid #666666;
  border-collapse: collapse;
  background-color: #cccccc;
  cursor: default;
  font-family: verdana;
  font-size: 12px;
}

table.zdp-calendar th {
  border: 1px solid #666666;
  font-weight: bold;
  background-color: #ff6666;
}

table.zdp-calendar td {
  border: 1px solid #666666;
  text-align: center;
}

table.zdp-calendar caption {
  background-color: #333333;
  padding: 2px;
}

span.zdp-current-month {
  display: inline-block;
  width: auto;
  height: 16px;
  padding: 0 2px;
  line-height: 16px;
  margin: 0 auto;
  background-color: #999999;
  border-radius: 5px;
}

span.zdp-increase-month, span.zdp-increase-year, span.zdp-decrease-month, span.zdp-decrease-year {
  display: block;
  padding: 0 2px;
  height: 16px;
  font-weight: bold;
  background-color: #999999;
  border-radius: 5px;
  cursor: pointer;
}

span.zdp-decrease-month, span.zdp-decrease-year {
  float: left;
  margin-right: 2px;
}

span.zdp-increase-month, span.zdp-increase-year {
  float: right;
  margin-left: 2px;
}

td.zdp-active-cell {
  padding: 1px 3px;
  cursor: pointer;
  color: #000000;
  text-align: center;
  vertical-align: middle;
}

td.zdp-active-cell:hover {
  background-color: #999999;
  cursor: pointer;
}

td.zdp-empty-cell {
  cursor: not-allowed;
}
</style>

</head>
<body>

<form name="myform">
  <p>
    From: <input type="text" readonly class="date-picker" name="date-from" />
    To: <input type="text" readonly class="date-picker" name="date-to" />
  </p>
</form>

</body>
</html>
Note: The current implementation of const (constant statement) is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8) and partially supported in Opera 9+ and Safari. It is not supported in Internet Explorer 6-9, or in the preview of Internet Explorer 10. const is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the let statement, constants declared with const will be block-scoped. We used it only for didactic purpose. If you want a full browser compatibility of this library, please replace all the const statements with the var statements.

This date-picker code snippet will automatically create an HTML code like the following:

<table id="zdp-cal-1" class="zdp-calendar" style="z-index: 1026; position: absolute; left: 294px; top: 47px;">
  <caption><span id="zdp-decr-year-1" class="zdp-decrease-year">&laquo;</span><span id="zdp-decr-month-1" class="zdp-decrease-month">&lt;</span><span id="zdp-incr-year-1" class="zdp-increase-year">&raquo;</span><span id="zdp-incr-month-1" class="zdp-increase-month">&gt;</span>
    <span class="zdp-current-month">Aug 1998</span>
  </caption>
  <thead>
    <tr>
      <th>M</th>
      <th>T</th>
      <th>W</th>
      <th>T</th>
      <th>F</th>
      <th>S</th>
      <th>S</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="zdp-empty-cell">&nbsp;</td>
      <td class="zdp-empty-cell">&nbsp;</td>
      <td class="zdp-empty-cell">&nbsp;</td>
      <td class="zdp-empty-cell">&nbsp;</td>
      <td class="zdp-empty-cell">&nbsp;</td>
      <td id="zdp-day-1-1" class="zdp-active-cell">1</td>
      <td id="zdp-day-1-2" class="zdp-active-cell">2</td>
    </tr>
    <tr>
      <td id="zdp-day-1-3" class="zdp-active-cell">3</td>
      <td id="zdp-day-1-4" class="zdp-active-cell">4</td>
      <td id="zdp-day-1-5" class="zdp-active-cell">5</td>
      <td id="zdp-day-1-6" class="zdp-active-cell">6</td>
      <td id="zdp-day-1-7" class="zdp-active-cell">7</td>
      <td id="zdp-day-1-8" class="zdp-active-cell">8</td>
      <td id="zdp-day-1-9" class="zdp-active-cell">9</td>
    </tr>
    <tr>
      <td id="zdp-day-1-10" class="zdp-active-cell">10</td>
      <td id="zdp-day-1-11" class="zdp-active-cell">11</td>
      <td id="zdp-day-1-12" class="zdp-active-cell">12</td>
      <td id="zdp-day-1-13" class="zdp-active-cell">13</td>
      <td id="zdp-day-1-14" class="zdp-active-cell">14</td>
      <td id="zdp-day-1-15" class="zdp-active-cell">15</td>
      <td id="zdp-day-1-16" class="zdp-active-cell">16</td>
    </tr>
    <tr>
      <td id="zdp-day-1-17" class="zdp-active-cell">17</td>
      <td id="zdp-day-1-18" class="zdp-active-cell">18</td>
      <td id="zdp-day-1-19" class="zdp-active-cell">19</td>
      <td id="zdp-day-1-20" class="zdp-active-cell">20</td>
      <td id="zdp-day-1-21" class="zdp-active-cell">21</td>
      <td id="zdp-day-1-22" class="zdp-active-cell">22</td>
      <td id="zdp-day-1-23" class="zdp-active-cell">23</td>
    </tr>
    <tr>
      <td id="zdp-day-1-24" class="zdp-active-cell">24</td>
      <td id="zdp-day-1-25" class="zdp-active-cell">25</td>
      <td id="zdp-day-1-26" class="zdp-active-cell">26</td>
      <td id="zdp-day-1-27" class="zdp-active-cell">27</td>
      <td id="zdp-day-1-28" class="zdp-active-cell">28</td>
      <td id="zdp-day-1-29" class="zdp-active-cell">29</td>
      <td id="zdp-day-1-30" class="zdp-active-cell">30</td>
    </tr>
    <tr>
      <td id="zdp-day-1-31" class="zdp-active-cell">31</td>
      <td class="zdp-empty-cell">&nbsp;</td>
      <td class="zdp-empty-cell">&nbsp;</td>
      <td class="zdp-empty-cell">&nbsp;</td>
      <td class="zdp-empty-cell">&nbsp;</td>
      <td class="zdp-empty-cell">&nbsp;</td>
      <td class="zdp-empty-cell">&nbsp;</td>
    </tr>
  </tbody>
</table>

Editable <select> fields

The content of the <select> element is actually static and not editable. If you want to emulate an editable select through a <fieldset> of radioboxes and textboxes (written in pure CSS, without JavaScript), please see this example.

Autogrowing <textarea>

This example shows how to make a textarea really autogrowing during a typing.

Insert some custom text in a <textarea>

This example shows how to insert some HTML tags or smiles or any custom text in a textarea.

Image preview before upload

The FileReader.prototype.readAsDataURL() method can be useful, for example, to get a preview of an image before uploading it.[article] This example shows how to use it in this way.

Note: The FileReader() constructor was not supported by Internet Explorer for versions before 10. For a full compatibility code you can see our crossbrowser possible solution for image preview.

Filter the digitation into a form field

This example shows the use of the onkeypress event during a digitation into a form field in order to match some rules.