The URL that processes the form submission. This value can be overridden by a formaction attribute
on a <button>, <input type="submit">, or <input type="image"> element.
It may also be overridden in javascript. This attribute is ignored when method="dialog" is set.
enctype
If the value of the method attribute is post, enctype is the MIME type of the form submission.
Possible values:
application/x-www-form-urlencoded: The default value.
multipart/form-data: Use this if the form contains <input> elements with type=file.
text/plain: Useful for debugging purposes.
This value can be overridden by formenctype attributes on <button>, <input
type="submit">, or <input type="image"> elements.
method
The HTTP method to submit the form with. The only allowed methods/values are (case insensitive):
post: The POST method; form data sent as the request body.
get (default): The GET; form data appended to the action URL with a ? separator. Use this method when the form has no side effects.
dialog: When the form is inside a <dialog>, closes the dialog and causes a submit event to be fired on submission, without submitting data or clearing the form.
This value is overridden by formmethod attributes on <button>, <input type="submit">, or
<input type="image"> elements, as well as javascript.
target
Indicates where to display the response after submitting the form. It is a name/keyword for a
browsing context (for example, tab, window, or iframe). The following keywords have special
meanings:
_self (default): Load into the same browsing context as the current one.
_blank: Load into a new unnamed browsing context. This provides the same behavior as setting rel="noopener" which does not set window.opener.
_parent: Load into the parent browsing context of the current one. If no parent, behaves the same as _self.
_top: Load into the top-level browsing context (i.e., the browsing context that is an ancestor of the current one and has no parent). If no parent, behaves the same as _self.
_unfencedTop: Load the response from a form inside an embedded fenced frame into the top-level frame (i.e., traversing beyond the root of the fenced frame, unlike other reserved destinations). Only available inside fenced frames.
This value can be overridden by a formtarget attribute on a <button>, <input type="submit">,
or <input type="image"> element.
Dynamic Creation
var someDiv = document.getElementById("someDiv");
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "FileOrPath");
/* ADD FORM ELEMENTS TO FORM ELEMENT HERE
form.appendChild(form_element);
*/
someDiv.appendChild(form);
Styling
A form can be styled as a container to encapsulate all of the form elements within it.
The following are a few of the CSS elements that can be used to style a form.
function addDynoBtn1(result_div) {
var divResult = document.getElementById(result_div);
var dyno_btn = document.createElement("input");
// SET ATTRIBUTES FOR DYNAMIC BUTTON
dyno_btn.setAttribute("type", "button");
dyno_btn.setAttribute("id", "dynobtn01");
dyno_btn.setAttribute("name", "dynobtn01");
dyno_btn.setAttribute("value", "Click Me");
dyno_btn.setAttribute("class", "btn btn-primary");
dyno_btn.onclick = function () {
alert("Dynamic Button Clicked");
};
divResult.appendChild(dyno_btn);
}
Response
Button Action
In order for a button to do anything, an action must be specified. This can either be done on the
button directly by using the onclick attribute in button and input type=button, and href in
the anchor button, or by setting up an click event using javascript.
A button can be styled using CSS elements. Note that with the Anchor Button, you'll need to also
supress the default underlined text. This can be done by setting the text-decoration to none.
Here are a few:
margin
border
border-radius
padding
color
background-color
text-decoration
Setting the button to change on hover. Often web UI designers will have the style of a button
change when the mouse hovers over it by using the :hover pseudo class. Here is an example:
The text box control, along with the button control is one of the most used of the HTML controls.
It is also the one with the most variations. This control is for the input of single line text.
Attributes
value
The value attribute is a string that contains the current value of the text entered into the
text field. You can retrieve this using the HTMLInputElement value property in JavaScript.
maxlength
The maximum string length (measured in UTF-16 code units) that the user can enter into the
text input. This must be an integer value of 0 or higher. If no maxlength is specified,
or an invalid value is specified, the text input has no maximum length. This value must
also be greater than or equal to the value of minlength.
The input will fail constraint validation if the length of the text value of the field is
greater than maxlength UTF-16 code units long. Constraint validation is only applied when
the value is changed by the user.
minlength
The minimum string length (measured in UTF-16 code units) that the user can enter into the
text input. This must be a non-negative integer value smaller than or equal to the value
specified by maxlength. If no minlength is specified, or an invalid value is specified,
the text input has no minimum length.
The input will fail constraint validation if the length of the text entered into the field is
fewer than minlength UTF-16 code units long. Constraint validation is only applied when the
value is changed by the user.
pattern
The pattern attribute, when specified, is a regular expression that the input's value must
match for the value to pass constraint validation. It must be a valid JavaScript regular
expression, as used by the RegExp type, and as documented in our guide on regular
expressions; the 'u' flag is specified when compiling the regular expression so that the
pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward
slashes should be specified around the pattern text.
If the specified pattern is not specified or is invalid, no regular expression is applied
and this attribute is ignored completely.
placeholder
The placeholder attribute is a string that provides a brief hint to the user as to what kind
of information is expected in the field. It should be a word or short phrase that demonstrates
the expected type of data, rather than an explanatory message. The text must not include
carriage returns or line feeds.
If the control's content has one directionality (LTR or RTL) but needs to present the placeholder
in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters
to override directionality within the placeholder; see How to use Unicode controls for bidi text
for more information.
readonly
A Boolean attribute which, if present, means this field cannot be edited by the user. Its value
can, however, still be changed by JavaScript code directly setting the HTMLInputElement value
property.
size
The size attribute is a numeric value indicating how many characters wide the input field should be.
The value must be a number greater than zero, and the default value is 20. Since character widths vary,
this may or may not be exact and should not be relied upon to be so; the resulting input may be
narrower or wider than the specified number of characters, depending on the characters and the
font (font settings in use).
This does not set a limit on how many characters the user can enter into the field. It only
specifies approximately how many can be seen at a time. To set an upper limit on the length
of the input data, use the maxlength attribute.
list
The values of the list attribute is the id of a <datalist> element located in the same document.
The <datalist> provides a list of predefined values to suggest to the user for this input.
Any values in the list that are not compatible with the type are not included in the suggested
options. The values provided are suggestions, not requirements: users can select from this
predefined list or provide a different value.
required
You can use the required attribute as an easy way of making entering a value required before
form submission is allowed.
Validation should not be done upon the input field, but indicators to the user whether their input
is valid or not are a fairly standard practice. This can be done using the required attribute
and / or the pattern attribute with a valid regular expression, and using the css pseudo-classes
:valid and :invalid.
<input> elements of type="date" create input fields that let the user enter a date.
The appearance of the date picker input UI varies based on the browser and operating system.
The value is normalized to the format yyyy-mm-dd.
The resulting value includes the year, month, and day, but not the time. The time and
datetime-local input types support time and date+time input.
Relevant Attributes
value
A string representing the date entered in the input. The date is formatted according
to Date strings format YYYY-MM-DD.
max
The latest date to accept. If the value entered into the element occurs afterward,
the element fails constraint validation. If the value of the max attribute isn't a
possible date string in the format yyyy-mm-dd, then the element has no maximum date
value.
If both the max and min attributes are set, this value must be a date string later
than or equal to the one in the min attribute.
min
The earliest date to accept. If the value entered into the element occurs beforehand,
the element fails constraint validation. If the value of the min attribute isn't a
possible date string in the format yyyy-mm-dd, then the element has no minimum date
value.
If both the max and min attributes are set, this value must be a date string earlier
than or equal to the one in the max attribute.
step
The step attribute is a number that specifies the granularity that the value must adhere to,
or the special value any, which is described below. Only values which are equal to the basis
for stepping (min if specified, value otherwise, and an appropriate default value if neither
of those is provided) are valid.
A string value of any means that no stepping is implied, and any value is allowed
(barring other constraints, such as min and max).
For date inputs, the value of step is given in days; and is treated as a number of milliseconds
equal to 86,400,000 times the step value (the underlying numeric value is in milliseconds).
The default value of step is 1, indicating 1 day.
<style>
#my_form4 fieldset {
margin:0rem;
border:1px solid #555;
border-radius: 5px;
padding:1.5rem;
background-color:rgba(0,133,242,0.1);
color:rgba(0,133,242,1);
}
#my_form4 fieldset legend {
width:auto;
float: none;
margin:0rem;
border:1px solid #555;
border-radius: 5px;
padding:0.5rem;
background-color:rgba(0,133,242,0.1);
color:rgba(0,133,242,1);
}
#my_form4 input[type="date"] {
margin:1rem 0rem 1rem 0rem;
border-top:1px solid #000;
border-right:1px solid #000;
border-bottom:1px solid #000;
border-left:3px solid #1C75BC;
border-radius:5px;
padding:0.5rem 1rem;
color:#1C75BC;
background-color:#fff;
}
</style>
<form id="my_form4" name="my_form4">
<fieldset>
<legend>Date Example</legend>
<label for="dateStart1">Date</label>
<input type="date" id="dateStart1" name="dateStart1" min="2025-01-01" max="2025-12-31" value="" class="myTxtBx2" required />
Only year 2025 can be selected.
<hr class="space2"/>
<label for="dateStep1">Date</label>
<input type="date" id="dateStep1" name="dateStep1" min="2025-01-04" max="2025-12-31" step="7" value="" class="myTxtBx2" required />
Only Saturdays in 2025 can be selected.
<hr class="space2"/>
<label for="dateAll1">Date</label>
<input type="date" id="dateAll1" name="dateAll1" min="2021-01-01" max="2035-12-31" step="any" value="" class="myTxtBx2" required />
Only dates between Jan 1, 2020 and Dec 31, 2035 can be selected.
</fieldset>
</form>
Getting Value
let start_date = document.getElementById("start_date").value; // YYYY-MM-DD
Setting Value
let start_date = document.getElementById("start_date");
let dt_now = new Date();
let month, day, year;
month = dt_now.getMonth() + 1;
day = dt_now.getDate();
year = dt_now.getFullYear();
start_date.value = year.toString() + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
Dynamic Creation
The following creates a date where the user can only input dates between today's date and two
months from today's date.
function addDynoDate1(result_div) {
let divResult = document.getElementById(result_div);
let dyno_date = document.createElement("input");
let dt_now = new Date();
let month, day, year;
month = dt_now.getMonth() + 1;
day = dt_now.getDate();
year = dt_now.getFullYear();
// SET ATTRIBUTES FOR TEXT BOX
dyno_date.setAttribute("type", "date");
dyno_date.setAttribute("id", "dynobtn01");
dyno_date.setAttribute("name", "dynobtn01");
dyno_date.setAttribute("class", "myTxtBx2");
dyno_date.setAttribute("value", year.toString() + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0"));
dyno_date.setAttribute("min", year.toString() + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0"));
if ((month + 2) >= 11) {
month = 1;
year += 1;
} else {
month += 2;
}
dyno_date.setAttribute("max", year.toString() + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0"));
divResult.appendChild(dyno_date);
}
Response
Styling
The styling for a date input box is pretty much the same as a regular text box.
<input> elements of type time create input fields designed to let the user easily enter a time
(hours and minutes, and optionally seconds).
While the control's user interface appearance is based on the browser and operating system,
the features are the same. The value is always a 24-hour HH:mm or HH:mm:ss formatted time,
with leading zeros, regardless of the UI's input format.
Relevant Attributes
Unlike many data types, time values have a periodic domain, meaning that the values reach the
highest possible value, then wrap back around to the beginning again. For example, specifying
a min of 14:00 and a max of 2:00 means that the permitted time values start at 2:00 PM, run
through midnight to the next day, ending at 2:00 AM.
value
The value of the time input is always in 24-hour format that includes leading zeros: HH:mm,
regardless of the input format, which is likely to be selected based on the user's locale
(or by the user agent). If the time includes seconds (see using the step attribute),
the format is always HH:mm:ss.
list
The values of the list attribute is the id of a <datalist> element located in the same document.
The <datalist> provides a list of predefined values to suggest to the user for this input.
Any values in the list that are not compatible with the type are not included in the suggested options.
The values provided are suggestions, not requirements: users can select from this predefined list or
provide a different value.
max
A string indicating the latest time to accept, specified in the same time value format as described
above. If the specified string isn't a valid time, no maximum value is set.
min
A string specifying the earliest time to accept, given in the time value format described previously.
If the value specified isn't a valid time string, no minimum value is set.
step
The step attribute is a number that specifies the granularity that the value must adhere to,
or the special value any, which is described below. Only values which are equal to the basis
for stepping (min if specified, value otherwise, and an appropriate default value if neither
of those is provided) are valid.
A string value of any means that no stepping is implied, and any value is allowed (barring
other constraints, such as min and max).
For time inputs, the value of step is given in seconds, with a scaling factor of 1000 (since
the underlying numeric value is in milliseconds). The default value of step is 60, indicating
60 seconds (or 1 minute, or 60,000 milliseconds).
When any is set as the value for step, the default 60 seconds is used, and the seconds value
is not displayed in the UI.
function getTime01(result_div) {
let divResult = document.getElementById(result_div);
let timeTest01 = document.getElementById("timeTest01");
divResult.innerHTML = "At the tone, the time will be: " + timeTest01.value;
}
Response
Setting Value
let timeTest01 = document.getElementById("timeTest01");
timeTest01.value = "21:05";
Dynamic Creation
function addDynoTime01(result_div) {
let divResult = document.getElementById(result_div);
let dyno_time = document.createElement("input");
let dt_now = new Date();
let hour, minutes, seconds;
hour = dt_now.getHours() + 1;
minutes = dt_now.getMinutes();
seconds = dt_now.getSeconds();
// SET ATTRIBUTES FOR TEXT BOX
dyno_time.setAttribute("type", "time");
dyno_time.setAttribute("id", "dynoTime01");
dyno_time.setAttribute("name", "dynoTime01");
dyno_time.setAttribute("class", "myTimeBx");
dyno_time.setAttribute("value", hour.toString().padStart(2, "0") + ":" + minutes.toString().padStart(2, "0"));
divResult.appendChild(dyno_time);
}
Response
Styling
The styling for a time input box is pretty much the same as a regular text box.
<input> elements of type datetime-local create input controls that let the user easily enter
both a date and a time, including the year, month, and day as well as the time in hours and minutes.
The control's UI varies in general from browser to browser. The control is intended to represent a
local date and time, not necessarily the user's local date and time. In other words, the input
allows any valid combination of year, month, day, hour, and minute—even if such a combination
is invalid in the user's local time zone (such as the one hour within a daylight saving time
spring-forward transition gap).
Attributes
value
A string representing the value of the date entered into the input. The format of the
date and time value used by this input type is described in Local date and time strings.
You can set a default value for the input by including a date and time inside the value
attribute, like so:
<label for="party">Enter a date and time for your party booking:</label>
<input
id="party"
type="datetime-local"
name="party-date"
value="2017-06-01T08:30" />
One thing to note is that the displayed date and time formats differ from the actual value;
the displayed date and time are formatted according to the user's locale as reported by their
operating system, whereas the date/time value is always formatted YYYY-MM-DDTHH:mm.
Also bear in mind that if such data is submitted via HTTP GET, the colon character will
need to be escaped for inclusion in the URL parameters, e.g., party-date=2024-06-01T08%3A30.
See encodeURI() for one way to do this.
max
The latest date and time to accept. If the value entered into the element is later than this
timestamp, the element fails constraint validation. If the value of the max attribute isn't a
valid string that follows the format YYYY-MM-DDTHH:mm, then the element has no maximum value.
This value must specify a date string later than or equal to the one specified by the min attribute.
min
The earliest date and time to accept; timestamps earlier than this will cause the element to
fail constraint validation. If the value of the min attribute isn't a valid string that
follows the format YYYY-MM-DDTHH:mm, then the element has no minimum value.
This value must specify a date string earlier than or equal to the one specified by the max attribute.
step
The step attribute is a number that specifies the granularity that the value must adhere to,
or the special value any, which is described below. Only values which are equal to the basis
for stepping (min if specified, value otherwise, and an appropriate default value if neither
of those is provided) are valid.
A string value of any means that no stepping is implied, and any value is allowed (barring
other constraints, such as min and max).
When the data entered by the user doesn't adhere to the stepping configuration,
the user agent may round to the nearest valid value, preferring numbers in the positive
direction when there are two equally close options.
For datetime-local inputs, the value of step is given in seconds, with a scaling factor
of 1000 (since the underlying numeric value is in milliseconds). The default value of
step is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds).
Getting Value
let date_time_local = document.getElementById("date_time_local");
let value = date_time_local.value;
Setting Value
let date_time_local = document.getElementById("date_time_local");
date_time_local.value = "2017-06-01T08:30";
Dynamic Creation
function addDynoDateTime1(result_div) {
let divResult = document.getElementById(result_div);
let dyno_date_time = document.createElement("input");
let dt_now = new Date();
let year, month, day, hour, minutes, seconds, dt_str;
year = dt_now.getFullYear();
month = dt_now.getMonth() + 1;
day = dt_now.getDate();
hour = dt_now.getHours() + 1;
minutes = dt_now.getMinutes();
seconds = dt_now.getSeconds();
dt_str = year.toString() + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0") + "T" + hour.toString().padStart(2, "0") + ":" + minutes.toString().padStart(2, "0");
// SET ATTRIBUTES FOR TEXT BOX
dyno_date_time.setAttribute("type", "datetime-local");
dyno_date_time.setAttribute("id", "dynoDateTime01");
dyno_date_time.setAttribute("name", "dynoDateTime01");
dyno_date_time.setAttribute("class", "myDateTimeBx");
dyno_date_time.setAttribute("value", dt_str);
divResult.appendChild(dyno_date_time);
}
Response
Styling
The styling for a datetime-local input box is pretty much the same as a regular text box.
<input> elements of type month create input fields that let the user enter a month and
year allowing a month and year to be easily entered. The value is a string whose value is in
the format YYYY-MM, where YYYY is the four-digit year and MM is the month number.
The control's UI varies in general from browser to browser; at the moment support is patchy,
with only Chrome/Opera and Edge on desktop, and most modern mobile browser versions, having
usable implementations. In browsers that don't support month inputs, the control degrades
gracefully to <input type="text">, although there may be automatic validation of the
entered text to ensure it's formatted as expected.
Attributes
value
A string representing the value of the month and year entered into the input,
in the form YYYY-MM (four or more digit year, then a hyphen (-), followed by
the two-digit month). The format of the month string used by this input type is
described in Month strings.
One thing to note is that the displayed date format differs from the actual value;
most user agents display the month and year in a locale-appropriate form, based on
the set locale of the user's operating system, whereas the date value is always
formatted yyyy-MM.
list
The values of the list attribute is the id of a <datalist> element located in the
same document. The <datalist> provides a list of predefined values to suggest to the
user for this input. Any values in the list that are not compatible with the type are not
included in the suggested options. The values provided are suggestions, not requirements:
users can select from this predefined list or provide a different value.
max
The latest year and month, in the string format discussed in the Value section above,
to accept. If the value entered into the element exceeds this, the element fails
constraint validation. If the value of the max attribute isn't a valid string in
yyyy-MM format, then the element has no maximum value.
This value must specify a year-month pairing later than or equal to the one specified
by the min attribute.
min
The earliest year and month to accept, in the same yyyy-MM format described above.
If the value of the element is less than this, the element fails constraint validation.
If a value is specified for min that isn't a valid year and month string, the input has
no minimum value.
This value must be a year-month pairing which is earlier than or equal to the one specified
by the max attribute.
step
The step attribute is a number that specifies the granularity that the value must adhere
to, or the special value any, which is described below. Only values which are equal to
the basis for stepping (min if specified, value otherwise, and an appropriate default
value if neither of those is provided) are valid.
A string value of any means that no stepping is implied, and any value is allowed
(barring other constraints, such as min and max).
When the data entered by the user doesn't adhere to the stepping configuration,
the user agent may round to the nearest valid value, preferring numbers in the
positive direction when there are two equally close options.
For month inputs, the value of step is given in months, with a scaling factor of 1
(since the underlying numeric value is also in months). The default value of step
is 1 month.
Getting Value
let month_year_bx = document.getElementById("month_year_bx");
let month_year = month_year_bx.value;
Setting Value
let month_year_bx = document.getElementById("month_year_bx");
month_year_bx.value = "2025-05";
Dynamic Creation
function addDynoMonth1(result_div) {
let divResult = document.getElementById(result_div);
let dyno_month = document.createElement("input");
let dt_now = new Date();
let year, month, month_str;
year = dt_now.getFullYear();
month = dt_now.getMonth() + 1;
month_str = year.toString() + "-" + month.toString().padStart(2, "0");
// SET ATTRIBUTES FOR TEXT BOX
dyno_month.setAttribute("type", "month");
dyno_month.setAttribute("id", "dynoMonth01");
dyno_month.setAttribute("name", "dynoMonth01");
dyno_month.setAttribute("class", "myDateTimeBx");
dyno_month.setAttribute("value", month_str);
divResult.appendChild(dyno_month);
}
Response
Styling
The styling for a month input box is pretty much the same as a regular text box.
<input> elements of type week create input fields allowing easy entry of a year plus
the ISO 8601 week number during that year (i.e., week 1 to 52 or 53).
The control's user interface varies from browser to browser; cross-browser support is
currently a bit limited, with only Chrome/Opera and Microsoft Edge supporting it at
this time. In non-supporting browsers, the control degrades gracefully to function
identically to <input type="text">.
Attributes
value
A string representing the value of the week/year entered into the input. The format
of the date and time value used by this input type is described in Week strings.
max
The latest (time-wise) year and week number, in the string format discussed in
the Value section above, to accept. If the value entered into the element exceeds
this, the element fails constraint validation. If the value of the max attribute
isn't a valid week string, then the element has no maximum value.
This value must be greater than or equal to the year and week specified by the min attribute.
min
The earliest year and week to accept. If the value of the element is less than this,
the element fails constraint validation. If a value is specified for min that isn't
a valid week string, the input has no minimum value.
This value must be less than or equal to the value of the max attribute.
step
The step attribute is a number that specifies the granularity that the value
must adhere to, or the special value any, which is described below. Only values
which are equal to the basis for stepping (min if specified, value otherwise,
and an appropriate default value if neither of those is provided) are valid.
A string value of any means that no stepping is implied, and any value is allowed
(barring other constraints, such as min and max).
When the data entered by the user doesn't adhere to the stepping configuration,
the user agent may round to the nearest valid value, preferring numbers in the
positive direction when there are two equally close options.
For week inputs, the value of step is given in weeks, with a scaling factor
of 604,800,000 (since the underlying numeric value is in milliseconds).
The default value of step is 1, indicating 1week. The default stepping
base is -259,200,000, which is the beginning of the first week of 1970
("1970-W01").
<label for="week">What week would you like to start?</label>
<input id="week" type="week" name="week" value="2017-W01" />
One thing to note is that the displayed format may differ from the actual value,
which is always formatted yyyy-Www. When the above value is submitted to the server,
for example, browsers may display it as Week 01, 2017, but the submitted value will
always look like week=2017-W01.
Getting Value
let week_txt_bx = document.getElementById("week_txt_bx");
let week_txt = week_txt_bx.value;
Setting Value
let week_txt_bx = document.getElementById("week_txt_bx");
week_txt_bx.value = "2025-W34";
Dynamic Creation
Date.prototype.getWeek = function (dowOffset) {
dowOffset = typeof (dowOffset) == 'number' ? dowOffset : 0;
var newYear = new Date(this.getFullYear(), 0, 1);
var day = newYear.getDay() - dowOffset;
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() -
(this.getTimezoneOffset() - newYear.getTimezoneOffset()) * 60000) / 86400000) + 1;
var weeknum;
if (day < 4) {
weeknum = Math.floor((daynum + day - 1) / 7) + 1;
if (weeknum > 52) {
nYear = new Date(this.getFullYear() + 1, 0, 1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
weeknum = nday < 4 ? 1 : 53;
}
}
else {
weeknum = Math.floor((daynum + day - 1) / 7);
}
return weeknum;
};
function addDynoWeek1(result_div) {
let divResult = document.getElementById(result_div);
let dyno_week = document.createElement("input");
let dt_now = new Date();
let year, week, week_str;
year = dt_now.getFullYear();
week = dt_now.getWeek();
week_str = year.toString() + "-W" + week.toString().padStart(2, "0");
// SET ATTRIBUTES FOR TEXT BOX
dyno_week.setAttribute("type", "week");
dyno_week.setAttribute("id", "dynoWeek01");
dyno_week.setAttribute("name", "dynoWeek01");
dyno_week.setAttribute("class", "myDateTimeBx");
dyno_week.setAttribute("value", week_str);
divResult.appendChild(dyno_week);
}
Response
Styling
The styling for a week input box is pretty much the same as a regular text box.
<input> elements of type number are used to let the user enter a number. They include
built-in validation to reject non-numerical entries.
The browser may opt to provide stepper arrows to let the user increase and decrease the value
using their mouse or by tapping with a fingertip.
Attributes
value
A number representing the value of the number entered into the input.
list
The values of the list attribute is the id of a <datalist> element located in the same document.
The <datalist> provides a list of predefined values to suggest to the user for this input.
Any values in the list that are not compatible with the type are not included in the suggested
options. The values provided are suggestions, not requirements: users can select from this
predefined list or provide a different value.
max
The maximum value to accept for this input. If the value entered into the element exceeds this,
the element fails constraint validation. If the value of the max attribute isn't a number,
then the element has no maximum value.
This value must be greater than or equal to the value of the min attribute.
min
The minimum value to accept for this input. If the value of the element is less than this,
the element fails constraint validation. If a value is specified for min that isn't a
valid number, the input has no minimum value.
This value must be less than or equal to the value of the max attribute.
step
The step attribute is a number that specifies the granularity that the value must adhere to,
or the special value any, which is described below. Only values which are equal to the basis
for stepping (min if specified, value otherwise, and an appropriate default value if neither
of those is provided) are valid.
A string value of any means that no stepping is implied, and any value is allowed (barring
other constraints, such as min and max).
When the data entered by the user doesn't adhere to the stepping configuration, the user
agent may round to the nearest valid value, preferring numbers in the positive direction
when there are two equally close options.
The default stepping value for number inputs is 1, allowing only integers to be entered—unless
the stepping base is not an integer.
Getting Value
let txtNumber = document.getElementById("txtNumber");
let my_number = txtNumber.value;
Setting Value
let txtNumber = document.getElementById("txtNumber");
txtNumber.value = "26";
Dynamic Creation
Response
Styling
The styling for a number input box is pretty much the same as a regular text box.
The <datalist> HTML element contains a set of <option> elements that represent the permissible
or recommended options available to choose from within other controls.
To bind the <datalist> element to the control, we give it a unique identifier in the id attribute,
and then add the list attribute to the <input> element with the same identifier as value. Only certain
types of <input> support this behavior, and it can also vary from browser to browser.
Each <option> element should have a value attribute, which represents a suggestion to be entered into
the input. It can also have a label attribute, or, missing that, some text content, which may be
displayed by the browser instead of value (Firefox), or in addition to value (Chrome and Safari,
as supplemental text). The exact content of the drop-down menu depends on the browser, but when
clicked, content entered into control field will always come from the value attribute.
<datalist> is not a replacement for <select>. A <datalist> does not represent
an input itself; it is a list of suggested values for an associated control. The control can
still accept any value that passes validation, even if it is not in this suggestion list.
Dynamic Creation
function addDynoDatalist1(result_div) {
let divResult = document.getElementById(result_div);
let dyno_textbox = document.createElement("input");
let dyno_datalist = document.createElement("datalist");
let option1 = document.createElement('option');
let option2 = document.createElement('option');
let option3 = document.createElement('option');
// SET ATTRIBUTES FOR TEXT BOX
dyno_textbox.setAttribute("type", "text");
dyno_textbox.setAttribute("id", "dynoText02");
dyno_textbox.setAttribute("name", "dynoText02");
dyno_textbox.setAttribute("class", "myTxtBx");
dyno_textbox.setAttribute("list", "dynoDatalist02");
dyno_textbox.setAttribute("value", "");
dyno_datalist.setAttribute("id", "dynoDatalist02");
dyno_datalist.setAttribute("name", "dynoDatalist02");
option1.text = "Vanilla";
option1.value = "Vanilla";
dyno_datalist.appendChild(option1);
option2.text = "Strawberry";
option2.value = "Strawberry";
dyno_datalist.appendChild(option2);
option3.text = "Chocolate";
option3.value = "Chocolate";
dyno_datalist.appendChild(option3);
divResult.appendChild(dyno_textbox);
divResult.appendChild(dyno_datalist);
}
Response
Range
<input> elements of type range let the user specify a numeric value which must be no less
than a given value, and no more than another given value. The precise value, however, is not
considered important. This is typically represented using a slider or dial control rather than
a text entry box like the number input type.
Because this kind of widget is imprecise, it should only be used if the control's exact value
isn't important.
Validation
There is no pattern validation available; however, the following forms of automatic validation
are performed:
If the value is set to something which can't be converted into a valid floating-point number,
validation fails because the input is suffering from a bad input.
The value won't be less than min. The default is 0.
The value won't be greater than max. The default is 100.
The value will be a multiple of step. The default is 1.
Attributes
value
The value attribute contains a string which contains a string representation of the selected number.
The value is never an empty string (""). The default value is halfway between the specified minimum
and maximum—unless the maximum is actually less than the minimum, in which case the default is set
to the value of the min attribute.
If an attempt is made to set the value lower than the minimum, it is set to the minimum. Similarly,
an attempt to set the value higher than the maximum results in it being set to the maximum.
max
The greatest value in the range of permitted values. If the value entered into the element
exceeds this, the element fails constraint validation. If the value of the max attribute
isn't a number, then the element has no maximum value.
This value must be greater than or equal to the value of the min attribute. See the HTML
max attribute.
min
The lowest value in the range of permitted values. If the value of the element is less
than this, the element fails constraint validation. If a value is specified for min
that isn't a valid number, the input has no minimum value.
This value must be less than or equal to the value of the max attribute.
If the min and max values are equal or the max value is lower than the min value the
user will not be able to interact with the range.
step
The step attribute is a number that specifies the granularity that the value must adhere to.
Only values that match the specified stepping interval (min if specified, value otherwise,
or an appropriate default value if neither of those is provided) are valid.
The step attribute can also be set to the any string value. This step value means that no
stepping interval is implied and any value is allowed in the specified range (barring other
constraints, such as min and max). See the Setting step to the any value example for how
this works in supported browsers.
When the value entered by a user doesn't adhere to the stepping configuration,
the user agent may round off the value to the nearest valid value, preferring to round
numbers up when there are two equally close options.
The default stepping value for range inputs is 1, allowing only integers to be entered,
unless the stepping base is not an integer; for example, if you set min to -10 and value
to 1.5, then a step of 1 will allow only values such as 1.5, 2.5, 3.5,… in the positive
direction and -0.5, -1.5, -2.5,… in the negative direction.
list
The value of the list attribute is the id of a <datalist> element located in the same document.
The <datalist> provides a list of predefined values to suggest to the user for this input.
Any values in the list that are not compatible with the type are not included in the suggested
options. The values provided are suggestions, not requirements: users can select from this
predefined list or provide a different value.
See the adding tick marks below for an example of how the options on a range are denoted in
supported browsers.
Adding tick marks
To add tick marks to a range control, include the list attribute, giving it the id
of a <datalist> element which defines a series of tick marks on the control.
Each point is represented using an <option> element with its value set to the
range's value at which a mark should be drawn.
You can label tick marks by giving the <option> elements label attributes.
However, the label content will not be displayed by default. You can use CSS to
show the labels and to position them correctly. Here's one way you could do this.
<input> elements of type color provide a user interface element that lets a user specify a color,
either by using a visual color picker interface or by entering the color into a text field in
#rrggbb hexadecimal format.
Only basic hexadecimal colors (without alpha channel) are allowed though CSS colors has more
formats, e.g., color names, functional notations and a hexadecimal format with an alpha channel.
The element's presentation may vary substantially from one browser and/or platform to another,
it might be a basic textual input that automatically validates to ensure that the color information
is entered in the proper format, or a platform-standard color picker, or some kind of custom color
picker window.
Choose your web site's colors:
Getting Value
function getColor8(result_div) {
let divResult = document.getElementById(result_div);
let head_color = document.getElementById("head_color").value;
let body_color = document.getElementById("body_color").value;
divResult.innerHTML = "Header Color: " + head_color + ", Body Color: " + body_color;
}
Setting Value
function setColor8() {
let head_color = document.getElementById("head_color");
let body_color = document.getElementById("body_color");
head_color.value = "#33ff33";
body_color.value = "#ff3333";
}
Dynamic Creation
function addDynoColor1(result_div) {
let divResult = document.getElementById(result_div);
let dyno_color = document.createElement("input");
// SET ATTRIBUTES FOR TEXT BOX
dyno_color.setAttribute("type", "color");
dyno_color.setAttribute("id", "dynoColor01");
dyno_color.setAttribute("name", "dynoColor01");
dyno_color.setAttribute("value", "#1C75BC");
divResult.appendChild(dyno_color);
}
The <textarea> HTML element represents a multi-line plain-text editing control, useful when
you want to allow users to enter a sizeable amount of free-form text, for example a comment on a
review or feedback form.
<label for="story">Tell us your story:</label>
<textarea id="story" name="story" rows="5" cols="33">It was a dark and stormy night...</textarea>
The above example demonstrates a number of features of <textarea>:
An id attribute to allow the <textarea> to be associated with a <label> element
for accessibility purposes
A name attribute to set the name of the associated data point submitted to the server when the
form is submitted.
rows and cols attributes to allow you to specify an exact size for the <textarea> to take.
Setting these is a good idea for consistency, as browser defaults can differ.
The <textarea> element specifies its content differently in HTML and JavaScript contexts:
In HTML, the initial content of a <textarea> is specified between its opening and closing tags, not as a value attribute.
In JavaScript, <textarea> elements have a value property that can be used to get or set the current content, and defaultValue to get and set its initial value (equivalent to accessing the HTML element's text content).
The <textarea> element also accepts several attributes common to form <input>s,
such as autocapitalize, autocomplete, autofocus, disabled,
placeholder, readonly, and required.
Attributes
autocapitalize
Controls whether inputted text is automatically capitalized and, if so, in what manner.
autocomplete
Controls whether entered text can be automatically completed by the browser.
Possible values are:
off: The user must explicitly enter a value into this field for every use, or the document
provides its own auto-completion method; the browser does not automatically complete the entry.
on: The browser can automatically complete the value based on values that the user has entered
during previous uses.
<token-list>: An ordered set of space-separated autofill detail tokens, optionally
preceded by a sectioning token, a billing or shipping grouping token, and/or a token
identifying the type of recipient.
<textarea> elements that don't specify the autocomplete attribute inherit the autocomplete on or
off status set on the <textarea>'s form owner. The form owner is either the <form> element that
this <textarea> element is a descendant of or the form element whose id is specified by the form
attribute of the input element. For more information, see the autocomplete attribute in <form>.
autocorrect
Controls whether automatic spelling correction and processing of text is enabled while the
user is editing this textarea. Permitted values are:
on: Enable automatic spelling correction and text substitutions.
off: Disable automatic spelling correction and text substitutions.
autofocus
This Boolean attribute lets you specify that a form control should have input focus when
the page loads. Only one form-associated element in a document can have this attribute specified.
cols
The visible width of the text control, in average character widths. If it is specified,
it must be a positive integer. If it is not specified, the default value is 20.
rows
The number of visible text lines for the control. If it is specified, it must be a
positive integer. If it is not specified, the default value is 2.
dirname
This attribute is used to indicate the text directionality of the element contents.
form
The form element that the <textarea> element is associated with (its "form owner").
The value of the attribute must be the id of a form element in the same document.
If this attribute is not specified, the <textarea> element must be a descendant
of a form element. This attribute enables you to place <textarea> elements anywhere
within a document, not just as descendants of form elements.
maxlength
The maximum string length (measured in UTF-16 code units) that the user can enter.
If this value isn't specified, the user can enter an unlimited number of characters.
minlength
The minimum string length (measured in UTF-16 code units) required that the user
should enter.
placeholder
A hint to the user of what can be entered in the control. Carriage returns or line-feeds
within the placeholder text must be treated as line breaks when rendering the hint.
Placeholders should only be used to show an example of the type of data that should be
entered into a form; they are not a substitute for a proper <label> element tied
to the input.
spellcheck
Specifies whether the <textarea> is subject to spell-checking by the underlying
browser/OS. The value can be:
true: Indicates that the element needs to have its spelling and grammar checked.
default: Indicates that the element is to act according to a default behavior, possibly based on the parent element's own spellcheck value.
false: Indicates that the element should not be spell-checked.
wrap
Indicates how the control should wrap the value for form submission.
Possible values are:
hard: The browser automatically inserts line breaks (CR+LF) so that each line is no
longer than the width of the control; the cols attribute must be specified for this
to take effect
soft: The browser ensures that all line breaks in the entered value are a CR+LF pair,
but no additional line breaks are added to the value.
off (Non-standard): Like soft but changes appearance to white-space: pre so line segments
exceeding cols are not wrapped and the <textarea> becomes horizontally scrollable.
If this attribute is not specified, soft is its default value.
Controlling whether a textarea is resizable
In most browsers, <textarea>s are resizable, you'll notice the drag handle in the right-hand corner,
which can be used to alter the size of the element on the page. This is controlled by the resize CSS property,
resizing is enabled by default, but you can explicitly disable it using a resize value of none:
textarea {
resize: none;
}
Styling valid and invalid values
Valid and invalid values of a <textarea> element (e.g., those within, and outside the
bounds set by minlength, maxlength, or required) can be highlighted using the :valid and :invalid
pseudo-classes. For example, to give your textarea a different border depending on whether it is
valid or invalid:
let myTextArea = document.getElementById("myTextArea");
let ta_val = myTextArea.value;
Setting Value
let myTextArea = document.getElementById("myTextArea");
myTextArea.value = "Some text";
Dynamic Creation
The textarea HTML element's value is not an attribute, but is
in the elemment's innerHTML.
function addDynoTextArea1(result_div) {
let divResult = document.getElementById(result_div);
let dyno_textarea = document.createElement("textarea");
// SET ATTRIBUTES FOR TEXT AREA
dyno_textarea.setAttribute("type", "color");
dyno_textarea.setAttribute("id", "dynoTextArea01");
dyno_textarea.setAttribute("name", "dynoTextArea01");
dyno_textarea.setAttribute("rows", "5");
dyno_textarea.setAttribute("cols", "40");
dyno_textarea.setAttribute("maxlength", "100");
dyno_textarea.innerHTML = "Some text here.";
divResult.appendChild(dyno_textarea);
}
Response
Styling
<textarea> is a replaced element, it has intrinsic dimensions, like a raster image.
By default, its display value is inline-block. Compared to other form elements it is
relatively easy to style, with its box model, fonts, color scheme, etc. being easily
manipulable using regular CSS.
Drop Down List
The <select> HTML element represents a control that provides a menu of options.
This control is commonly called a drop-down list.
The above example shows typical <select> usage. It is given an id attribute to enable it
to be associated with a <label> for accessibility purposes, as well as a name attribute
to represent the name of the associated data point submitted to the server. Each menu option
is defined by an <option> element nested inside the <select>.
Each <option> element should have a value attribute containing the data value to submit
to the server when that option is selected. If no value attribute is included, the value defaults
to the text contained inside the element. You can include a selected attribute on an <option>
element to make it selected by default when the page first loads. If no selected attribute is
specified, the first <option> element will be selected by default.
A <select> element is represented in JavaScript by an HTMLSelectElement object, and this
object has a value property which contains the value of the selected <option>.
The <select> element has some unique attributes you can use to control it, such as multiple
to specify whether multiple options can be selected, and size to specify how many options should
be shown at once. It also accepts most of the general form input attributes such as required,
disabled, autofocus, etc.
You can further nest <option> elements inside <optgroup> elements to create separate
groups of options inside the dropdown. You can also include <hr> elements to create
separators that add visual breaks between options.
Attributes
form
The <form> element to associate the <select> with (its form owner). The value of
this attribute must be the id of a <form> in the same document. (If this attribute is
not set, the <select> is associated with its ancestor <form> element, if any.)
This attribute lets you associate <select> elements to <form>s anywhere in the
document, not just inside a <form>. It can also override an ancestor <form>
element.
multiple
This Boolean attribute indicates that multiple options can be selected in the list.
If it is not specified, then only one option can be selected at a time. When multiple
is specified, most browsers will show a scrolling list box instead of a single line dropdown.
size
If the control is presented as a scrolling list box (e.g., when multiple is specified),
this attribute represents the number of rows in the list that should be visible at one
time. Browsers are not required to present a select element as a scrolled list box.
The default value is 0.
Select with grouping options
The following example creates a dropdown menu with grouping using <optgroup> and
<hr> to make it easier for the user to understand the content in the dropdown.
The Option Group Element
The <optgroup> HTML element creates a grouping of options within a <select>
element.
In customizable <select> elements, the <legend> element is allowed as a child of
<optgroup>, to provide a label that is easy to target and style. This replaces any text
set in the <optgroup> element's label attribute, and it has the same semantics.
Attributes
disabled
If this Boolean attribute is set, none of the items in this option group is selectable.
Often browsers grey out such control and it won't receive any browsing events, like mouse
clicks or focus-related ones.
label
The name of the group of options, which the browser can use when labeling the options
in the user interface. This attribute is mandatory if this element is used.
The <select> element is a container for an array of values and text. Getting the value
or values that are selected is not as straight forward as it is with text box controls.
The control allows for mutiple selections when the multiple boolean attribute is set.
Most of the time it will only allow the selection of a single item.
The Options Array
When getting the value and or text of the selected item, you will need to address the
options array. The options array has a few attributes that can be referenced. In the
following, we will assume that the name and id of the <select> is list1.
options - An array of items in the list. Referred by list1.options
length - The number of items in the list. Referred by list1.options.length
selectedIndex - The currently selected item. Referred by list1.options.selectedIndex
text - A list item's text. Referred by list1.options[index].text
value - A list item's value. Referred by list1.options[index].value
It's not often that you will need to change a value in a drop down list, but if you do, the
following will work. Note that to deselect a list, you can set the options selectedIndex to
-1. Here we set it to 0 because that is an empty instructional element.
function setDdlSel2(result_div) {
let divResult = document.getElementById(result_div);
let cuisine_list = document.getElementById("cuisine_list2");
cuisine_list.options[cuisine_list.options.selectedIndex].text = "Changed Text";
cuisine_list.options[cuisine_list.options.selectedIndex].value = "changed_val";
cuisine_list.options.selectedIndex = 0;
divResult.innerHTML = "Selected Item Values Changed";
}
Dynamic Creation
function addDynoDdl1(result_div) {
let divResult = document.getElementById(result_div);
let my_ddl = document.createElement("select");
let my_data = [{ value:"101", text:"The Clash" },
{ value:"223", text:"Thompson Twins" },
{ value:"335", text:"Romeo Void" },
{ value:"434", text:"Dave Brubeck" },
{ value:"354", text:"INXS" }
];
let opt;
for (let i = 0; i < my_data.length; i++) {
let band_obj = my_data[i];
opt = new Option(band_obj.text, band_obj.value);
my_ddl.appendChild(opt);
}
divResult.appendChild(my_ddl);
}
A listbox is a regular dropdown list with the multiple boolean set and is most often styled
to show more than one line.
Getting Values
function getMutiLbx1(result_div) {
let divResult = document.getElementById(result_div);
let speakeasy1 = document.getElementById("speakeasy1");
let drinksList = "";
let counter = 0;
if (speakeasy1.options.selectedIndex == -1) {
divResult.innerHTML = "Nothing is Selected";
} else {
for (let i = 0; i < speakeasy1.options.length; i++) {
if (speakeasy1.options[i].selected == true) {
counter++;
drinksList += "Drink " + counter + " - " + speakeasy1.options[i].text + "<br/>";
}
}
divResult.innerHTML = drinksList;
}
}
Using Multiple Listboxes
In this example we have two list boxes side by side. Selecting items in the left list box (list-1)
and clicking on the Move To button will remove those items from list-1 and put them in
list-2. Selecting items in the right list box (list-2) and clicking on the Move Back
button will remove those items from list-2 and put them in list-1.
document.addEventListener('DOMContentLoaded', () => {
function mllMoveItemsTo() {
let ddBandList1 = document.getElementById("band-select3");
let ddBandList2 = document.getElementById("band-select4");
moveSelectedOptions(ddBandList1, ddBandList2);
};
function mllMoveItemsBack() {
let ddBandList1 = document.getElementById("band-select3");
let ddBandList2 = document.getElementById("band-select4");
moveSelectedOptions(ddBandList2, ddBandList1);
};
/****************************************************************************/
/* MOVES OPTIONS BETWEEN SELECT BOXES.
* PASSES SELECTED OPTIONS FROM from TO to AND RE-SORTS EACH.
* IF 3RD ARG 'false' IS PASSED, THEN THE LISTS ARE NOT SORTED AFTER THE MOVE.
* IF 4TH REG-EXP IS PASSED, THIS WILL FUNCTION TO MATCH AGAINST THE TEXT.
* IF THE TEXT OF AN OPTION MATCHES THE PATTERN, IT WILL NOT BE MOVED.
* IT WILL BE TREATED AS AN UNMOVEABLE OPTION.
*
* moveSelectedOptions( from,
* to,
* * autosort,
* * regex )
*
* PARAMETERS:
*
* from........SOURCE LIST
* to..........DESTINATION LIST
* autosort....BOOLEAN (OPTIONAL)
* regex.......A REGULAR EXPRESSION (OPTIONAL)
*/
function moveSelectedOptions(from, to) {
// UN-SELECT MATCHING OPTIONS, IF REQUIRED
if (arguments.length > 3) {
var regex = arguments[3];
if (regex != "") {
unSelectMatchingOptions(from, regex);
}
}
// MOVE THEM OVER
if (!hasOptions(from)) { return; }
for (var i = 0; i < from.options.length; i++) {
var o = from.options[i];
if (o.selected) {
if (!hasOptions(to)) { var index = 0; } else { var index = to.options.length; }
to.options[index] = new Option(o.text, o.value, false, false);
}
}
// DELETE THEM FROM ORIGINAL
for (var i = (from.options.length - 1); i >= 0; i--) {
var o = from.options[i];
if (o.selected) {
from.options[i] = null;
}
}
if ((arguments.length < 3) || (arguments[2] == true)) {
sortSelect(from);
sortSelect(to);
}
from.selectedIndex = -1;
to.selectedIndex = -1;
}
/****************************************************************************/
/* UNSELECTS ALL OPTIONS THAT MATCH THE REGULAR EXPRESSION
*
* unSelectMatchingOptions( select_object,
* regex )
* PARAMETERS:
*
* select_object....SELECT LIST
* regex............A REGULAR EXPRESSION
*/
function unSelectMatchingOptions(obj, regex) {
selectUnselectMatchingOptions(obj, regex, "unselect", false);
}
/* SELECTS ALL OPTIONS THAT MATCH THE REGULAR EXPRESSION
* DOES NOT AFFECT CURRENT SELECTED OPTIONS
*
* selectMatchingOptions( select_object,
* regex )
* PARAMETERS:
*
* select_object....SELECT LIST
* regex............A REGULAR EXPRESSION
*/
function selectMatchingOptions(obj, regex) {
selectUnselectMatchingOptions(obj, regex, "select", false);
}
/* SELECTS OR UNSELECTS OPTIONS USING A REGULAR EXPRESSION
*
* SYNTAX:
*
* selectUnselectMatchingOptions( select_object,
* regex,
* select/unselect,
* true/false )
* PARAMETERS:
* obj.......A SELECT LIST BOX
* regex.....A REGULAR EXPREESSION
* which.....A DIRECTIVE TO SELECT OR UNSELECT
* only......BOOLEAN
*/
function selectUnselectMatchingOptions(obj, regex, which, only) {
if (window.RegExp) {
if (which == "select") {
var selected1 = true;
var selected2 = false;
} else if (which == "unselect") {
var selected1 = false;
var selected2 = true;
} else {
return;
}
var re = new RegExp(regex);
if (!hasOptions(obj)) { return; }
for (var i = 0; i < obj.options.length; i++) {
if (re.test(obj.options[i].text)) {
obj.options[i].selected = selected1;
} else {
if (only == true) {
obj.options[i].selected = selected2;
}
}
}
}
}
/****************************************************************************/
/* UTILITY FUNCTION:
* TO DETERMINE IF A SELECT OBJECT HAS AN OPTIONS ARRAY
* IN OTHER WORDS, TO DETERMINE IF IT IS EMPTY
*/
function hasOptions(obj) {
if (obj != null && obj.options != null) { return true; }
return false;
}
/****************************************************************************/
/* SORTS OPTIONS IN LIST ALPHABETICALLY
*
* sortSelect( select_object )
*
* PARAMETER: select_object....SELECT LIST
*/
function sortSelect(obj) {
var o = new Array();
if (!hasOptions(obj)) { return; }
for (var i = 0; i < obj.options.length; i++) {
o[o.length] = new Option(obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected);
}
if (o.length == 0) { return; }
o = o.sort(
function (a, b) {
if ((a.text + "") < (b.text + "")) { return -1; }
if ((a.text + "") > (b.text + "")) { return 1; }
return 0;
}
);
for (var i = 0; i < o.length; i++) {
obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
}
}
document.getElementById("mlList2").addEventListener("click", mllMoveItemsTo);
document.getElementById("mlList3").addEventListener("click", mllMoveItemsBack);
});
The same styling for single select drop down lists apply for multiple select list boxes.
Radio Button
<input> elements of type radio are generally used in radio groups, collections of radio
buttons describing a set of related options.
Only one radio button in a given group can be selected at the same time. Radio buttons are
typically rendered as small circles, which are filled or highlighted when selected.
Checkboxes are similar to radio buttons, but with an important distinction: radio buttons
are designed for selecting one value out of a set, whereas checkboxes let you turn individual
values on and off. Where multiple controls exist, radio buttons allow one to be selected out
of them all, whereas checkboxes allow multiple values to be selected.
Attributes
value
The value attribute is a string containing the radio button's value. The value is never
shown to the user by their user agent. Instead, it's used to identify which radio button
in a group is selected.
name
A radio group is defined by giving each of radio buttons in the group the same name.
Once a radio group is established, selecting any radio button in that group automatically
deselects any currently-selected radio button in the same group.
You can have as many radio groups on a page as you like, as long as each has its own
unique name.
For example, if your form needs to ask the user for their preferred contact method,
you might create three radio buttons, each with the name property set to contact but
one with the value email, one with the value phone, and one with the value mail.
The user never sees the value or the name.
checked
A Boolean attribute which, if present, indicates that this radio button is the default
selected one in the group.
Data Representation of a Radio Group
When the above form is submitted with a radio button selected, the form's data includes an entry
in the form contact_method=value. This is the name and value attributes. For example, if the
user clicks on the "Phone" radio button then submits the form, the form's data will include
the line contact_method=phone.
If you omit the value attribute in the HTML, the submitted form data assigns the value on to
the group. In this scenario, if the user clicked on the "Phone" option and submitted the form,
the resulting form data would be contact=on, which isn't helpful. So don't forget to set your
value attributes!
If no radio button is selected when the form is submitted, the radio group is not included in
the submitted form data at all, since there is no value to report.
It's fairly uncommon to actually want to allow the form to be submitted without any of the
radio buttons in a group selected, so it is usually wise to have one default to the checked
state.
Getting Value
When the form is submitted, the name and value of the checked item is sent.
To get the value of the checked item before submission, you'll neen to iterate
through all of the items to find the checked button.
function getRadio1(result_div) {
let divResult = document.getElementById(result_div);
let rbtns = document.getElementsByName("contact_method");
let rb_checked_val = "";
for (let i = 0; i < rbtns.length; i++) {
if (rbtns[i].checked == true) {
rb_checked_val = rbtns[i].value;
}
}
divResult.innerHTML = "Checked Value: " + rb_checked_val;
}
Setting Value
Theres probably not a lot of need to set the value of a radio button or change the text of its
label, but if you need to, here's how you can do it. Check the radio buttons above after
clicking the button.
function setRadio1(result_div) {
let divResult = document.getElementById(result_div);
let rbtns = document.getElementsByName("contact_method");
for (let i = 0; i < rbtns.length; i++) {
if (rbtns[i].checked == true) {
rbtns[i].value = "Checked";
setCheckedLabel(rbtns[i].id, "Checked");
}
}
divResult.innerHTML = "Checked Set";
}
function setCheckedLabel(input_id_val, set_text) {
let qString = "label[for='" + input_id_val +"']";
let label = document.querySelector(qString);
label.innerHTML = set_text;
}
<input> elements of type checkbox are rendered by default as boxes that are checked
(ticked) when activated, like you might see in an official government paper form. The exact
appearance depends upon the operating system configuration under which the browser is running.
Generally this is a square but it may have rounded corners. A checkbox allows you to select
single values for submission in a form (or not). Checkboxes are a toggle control.
Attributes
value
A string representing the value of the checkbox. This is not displayed on the client-side,
but on the server this is the value given to the data submitted with the checkbox's name.
The value attribute is one which all <input>s share; however, it serves a special
purpose for inputs of type checkbox: when a form is submitted, only checkboxes which are
currently checked are submitted to the server, and the reported value is the value of the
value attribute. If the value is not otherwise specified, it is the string on by default.
checked
A boolean attribute indicating whether this checkbox is checked by default (when the page loads).
It does not indicate whether this checkbox is currently checked: if the checkbox's state is changed,
this content attribute does not reflect the change. (Only the HTMLInputElement's checked IDL attribute
is updated.)
Unlike other input controls, a checkbox's value is only included in the submitted data
if the checkbox is currently checked. If it is, then the value of the checkbox's value
attribute is reported as the input's value, or on if no value is set. If you want the
value sent whether checked or not, you'll need to add that to the body or querystring
manually via javascript.
String.prototype.capitalizeFirstLetter = function () {
return this.charAt(0).toUpperCase() + this.slice(1);
}
function getCbx1(result_div) {
let divResult = document.getElementById(result_div);
let cbxs = document.getElementsByName("instruments");
let rtnStr = "";
for (let i = 0; i < cbxs.length; i++) {
if (cbxs[i].checked == true) {
rtnStr += "Plays "+ cbxs[i].value.capitalizeFirstLetter() +"<br/>";
} else {
rtnStr += "Does Not Play " + cbxs[i].value.capitalizeFirstLetter() + "<br/>";
}
}
divResult.innerHTML = rtnStr;
}
Setting Value
Theres probably not a lot of need to set the value of a checkbox or change the text of its
label, but if you need to, here's how you can do it. This is very similar to changing a
radio button's value and its label.
function setCheckbox1(result_div) {
let divResult = document.getElementById(result_div);
let cbxs = document.getElementsByName("instruments");
for (let i = 0; i < cbxs.length; i++) {
if (cbxs[i].checked == true) {
cbxs[i].value = "Checked";
setCheckedLabel(cbxs[i].id, "Checked");
}
}
divResult.innerHTML = "Checked Set";
}
function setCheckedLabel(input_id_val, set_text) {
let qString = "label[for='" + input_id_val +"']";
let label = document.querySelector(qString);
label.innerHTML = set_text;
}