How to set HTML5 required attribute in Javascript?
Short version
element.setAttribute("required", ""); //turns required on
element.required = true; //turns required on through reflected attribute
jQuery(element).attr('required', ''); //turns required on
$("#elementId").attr('required', ''); //turns required on
element.removeAttribute("required"); //turns required off
element.required = false; //turns required off through reflected attribute
jQuery(element).removeAttr('required'); //turns required off
$("#elementId").removeAttr('required'); //turns required off
if (edName.hasAttribute("required")) { } //check if required
if (edName.required) { } //check if required using reflected attribute
Long Version
Once T.J. Crowder managed to point out reflected properties, i learned that following syntax is wrong:
element.attributes["name"] = value; //bad! Overwrites the HtmlAttribute object
element.attributes.name = value; //bad! Overwrites the HtmlAttribute object
value = element.attributes.name; //bad! Returns the HtmlAttribute object, not its value
value = element.attributes["name"]; //bad! Returns the HtmlAttribute object, not its value
You must go through element.getAttribute
and element.setAttribute
:
element.getAttribute("foo"); //correct
element.setAttribute("foo", "test"); //correct
This is because the attribute actually contains a special HtmlAttribute object:
element.attributes["foo"]; //returns HtmlAttribute object, not the value of the attribute
element.attributes.foo; //returns HtmlAttribute object, not the value of the attribute
By setting an attribute value to "true", you are mistakenly setting it to a String object, rather than the HtmlAttribute object it requires:
element.attributes["foo"] = "true"; //error because "true" is not a HtmlAttribute object
element.setAttribute("foo", "true"); //error because "true" is not an HtmlAttribute object
Conceptually the correct idea (expressed in a typed language), is:
HtmlAttribute attribute = new HtmlAttribute();
attribute.value = "";
element.attributes["required"] = attribute;
This is why:
getAttribute(name)
setAttribute(name, value)
exist. They do the work on assigning the value to the HtmlAttribute object inside.
On top of this, some attribute are reflected. This means that you can access them more nicely from Javascript:
//Set the required attribute
//element.setAttribute("required", "");
element.required = true;
//Check the attribute
//if (element.getAttribute("required")) {...}
if (element.required) {...}
//Remove the required attribute
//element.removeAttribute("required");
element.required = false;
What you don't want to do is mistakenly use the .attributes
collection:
element.attributes.required = true; //WRONG!
if (element.attributes.required) {...} //WRONG!
element.attributes.required = false; //WRONG!
Testing Cases
This led to testing around the use of a required
attribute, comparing the values returned through the attribute, and the reflected property
document.getElementById("name").required;
document.getElementById("name").getAttribute("required");
with results:
HTML .required .getAttribute("required")
========================== =============== =========================
<input> false (Boolean) null (Object)
<input required> true (Boolean) "" (String)
<input required=""> true (Boolean) "" (String)
<input required="required"> true (Boolean) "required" (String)
<input required="true"> true (Boolean) "true" (String)
<input required="false"> true (Boolean) "false" (String)
<input required="0"> true (Boolean) "0" (String)
Trying to access the .attributes
collection directly is wrong. It returns the object that represents the DOM attribute:
edName.attributes["required"] => [object Attr]
edName.attributes.required => [object Attr]
This explains why you should never talk to the .attributes
collect directly. You're not manipulating the values of the attributes, but the objects that represent the attributes themselves.
How to set required?
What's the correct way to set required
on an attribute? You have two choices, either the reflected property, or through correctly setting the attribute:
element.setAttribute("required", ""); //Correct
edName.required = true; //Correct
Strictly speaking, any other value will "set" the attribute. But the definition of Boolean
attributes dictate that it should only be set to the empty string ""
to indicate true. The following methods all work to set the required
Boolean attribute,
but do not use them:
element.setAttribute("required", "required"); //valid, but not preferred
element.setAttribute("required", "foo"); //works, but silly
element.setAttribute("required", "true"); //Works, but don't do it, because:
element.setAttribute("required", "false"); //also sets required boolean to true
element.setAttribute("required", false); //also sets required boolean to true
element.setAttribute("required", 0); //also sets required boolean to true
We already learned that trying to set the attribute directly is wrong:
edName.attributes["required"] = true; //wrong
edName.attributes["required"] = ""; //wrong
edName.attributes["required"] = "required"; //wrong
edName.attributes.required = true; //wrong
edName.attributes.required = ""; //wrong
edName.attributes.required = "required"; //wrong
How to clear required?
The trick when trying to remove the required
attribute is that it's easy to accidentally turn it on:
edName.removeAttribute("required"); //Correct
edName.required = false; //Correct
With the invalid ways:
edName.setAttribute("required", null); //WRONG! Actually turns required on!
edName.setAttribute("required", ""); //WRONG! Actually turns required on!
edName.setAttribute("required", "false"); //WRONG! Actually turns required on!
edName.setAttribute("required", false); //WRONG! Actually turns required on!
edName.setAttribute("required", 0); //WRONG! Actually turns required on!
When using the reflected .required
property, you can also use any "falsey" values to turn it off, and truthy values to turn it on. But just stick to true and false for clarity.
How to check for required
?
Check for the presence of the attribute through the .hasAttribute("required")
method:
if (edName.hasAttribute("required"))
{
}
You can also check it through the Boolean reflected .required
property:
if (edName.required)
{
}
HTML5 'Required' attribute for form validation: Good idea or bad idea
Client-side form validation is a good way for enhancing user experience, it also provides some styling that can help to communicate that an input is required.
But you will allways still have to validate any data submitted on the server, making sure is clean and safe data. The required
attribute can be manipulated by a malicious user.
Required attribute HTML5
I just ran into this issue with Safari 5 and it has been an issue with Opera 10 for some time, but I never spent time to fix it. Now I need to fix it and saw your post but no solution yet on how to cancel the form. After much searching I finally found something:
http://www.w3.org/TR/html5/forms.html#attr-fs-formnovalidate
<input type=submit formnovalidate name=cancel value="Cancel">
Works on Safari 5 and Opera 10.
HTML5 required attribute seems not working
Try putting it inside a form tag and closing the input tag:
<form>
<input type = "text" class = "txtPost" placeholder = "Post a question?" required />
<button class = "btnPost btnBlue">Post</button>
</form>
HTML5 required attribute one of two fields
Update 2020-06-21 (ES6):
Given that jQuery has become somewhat unfashionable in the JavaScript world and that ES6 provides some nice syntactic sugar, I have written a pure JS equivalent to the original answer:
document.addEventListener('DOMContentLoaded', function() {
const inputs = Array.from(
document.querySelectorAll('input[name=telephone], input[name=mobile]')
);
const inputListener = e => {
inputs
.filter(i => i !== e.target)
.forEach(i => (i.required = !e.target.value.length));
};
inputs.forEach(i => i.addEventListener('input', inputListener));
});
<form method="post">
Telephone:
<input type="tel" name="telephone" value="" required>
<br>Mobile:
<input type="tel" name="mobile" value="" required>
<br>
<input type="submit" value="Submit">
</form>
How to add HTML5 'required' attribute to woocommerce_form_field
If you actually want to change <input..
to <input required..
then you can add the woocommerce_form_field_checkbox
filter hook.
The fact is that where the HTML code is created
(This code was copied from wc-template-functions.php
line 2799)
<input type="' . esc_attr( $args['type'] ) . '" class="input-checkbox ' . esc_attr( implode( ' ', $args['input_class'] ) ) . '" name="' . esc_attr( $key ) . '" id="' . esc_attr( $args['id'] ) . '" value="1" ' . checked( $value, 1, false ) . ' /> ' . $args['label'] . $required . '</label>';
the option exists to add arguments to the existing $args
but not extra HTML
code to the HTML
itself
So if you add the code below to your existing code, you have the option to adjust the HTML
output from the $field
- str_replace - Replace all occurrences of the search string with the replacement string
function filter_woocommerce_form_field_checkbox( $field, $key, $args, $value ) {
// Based on key
if ( $key == 'privacy_policy_reg' ) {
$field = str_replace( '<input', '<input required', $field );
}
return $field;
}
add_filter( 'woocommerce_form_field_checkbox', 'filter_woocommerce_form_field_checkbox', 10, 4 );
Related: How should I change the woocommerce_form_field HTML Structure?
Can I apply the required attribute to select fields in HTML5?
Mandatory: Have the first value empty - required works on empty values
Prerequisites: correct html5 DOCTYPE and a named input field
<select name="somename" required>
<option value="">Please select</option>
<option value="one">One</option>
</select>
As per the documentation (the listing and bold is mine)
The required attribute is a boolean
attribute.
When specified, the user
will be required to select a value
before submitting the form.If a select element
- has a required attribute specified,
- does not have a multiple attribute specified,
- and has a display size of 1 (do not have SIZE=2 or more - omit it if not needed);
- and if the value
of the first option element in the
select element's list of options (if
any) is the empty string (i.e. present asvalue=""
),- and that
option element's parent node is the
select element (and not an optgroup
element),
then that option is the
select element's placeholder label
option.
html form - `required` attribute not triggered with onclick confirm
Try using onsubmit
on your <form>
rather than the button.
<h2>Form Two </h2><form method="post" action="example.com" id="delete_page" onsubmit="return confirm('Are you sure you want to submit?')">
Name : <input type="name" required><br> <input type="button" value="Cancel"> <input type="submit" value="Delete">
</form>
Related Topics
Pure CSS Multi-Level Drop-Down Menu
Having Google Chrome Repeat Table Headers on Printed Pages
Animate/Shrink Navbar on Scroll Using Bootstrap
How to Display Raw HTML Code in Pre or Something Like It But Without Escaping It
How to Vertically Align into the Center of the Content of a Div with Defined Width/Height
How to Determine Height of Content-Box of a Block and Inline Element
Make Div's Height Expand with Its Content
Rounded Table Corners CSS Only
Why Is Text Wrapping Around a Floating Element Instead of Going Belows Like Another Div
Colspan/Rowspan For Elements Whose Display Is Set to Table-Cell
Html: How to Have a Form Tag in Each Table Row in a Xhtml Valid Way
Responsive CSS Trapezoid Shape
How to Align Two Divs Horizontally
Drawing Text to <Canvas> with @Font-Face Does Not Work at the First Time
CSS Transform Origin Issue on Svg Sub-Element