If the field was originally marked as required:
How to set HTML5's required attribute using Javascript?-PHP Chinese Network Q&A
How to set HTML5's required attribute using Javascript?
P粉739886290
P粉739886290 2023-10-13 08:52:25
0
2
695

I'm trying to mark atextinput box asrequiredin Javascript.

If the field was originally markedrequired:

 

When the user attempts to submit, they receive a validation error:

But now I want to set therequiredproperty at "runtime" via Javascript:


Use the corresponding script:

//recommended W3C HTML5 syntax for boolean attributes document.getElementById("edName").attributes["required"] = "";

No validation checks, no blocking unless I submit now.

SettingsWhat is thecorrectway to validate Boolean attributesin HTML5?

jsFiddle

What is the value of this attribute you ask?

HTML5 ValidationrequiredAttributes logged asBoolean:

4.10.7.3.4requiredProperties

requiredThe property is a Boolean property. When specified, this element is required.

There are a lot of annoying things about how to definebooleanproperties. HTML5 specification comments:

The presence of a Boolean attribute on the

element represents a true value, and the absence of this attribute represents a false value.

If the attribute is present, its value must be the empty string or an ASCII case-insensitive value that matches the attribute's canonical name and has no leading or trailing spaces.

This means you can specify therequiredbooleanattribute in two different ways:

edName.attributes.required = ""; //the empty string edName.attributes.required = "required"; //the attribute's canonical name

But what is the value of the attributeactually?

When you look at my jsFiddle for this question, you'll notice that if therequiredattribute is defined in the tag:

Then the value of the attributeis not an empty string, nor is it the canonical name of the attribute:

edName.attributes.required = [object Attr]

This may lead to a solution.

P粉739886290
P粉739886290

reply all (2)
P粉269847997

requiredis areflective attribute(e.g.id,name,type, etc.), so:

element.required = true;

...whereelementis the actualinputDOM element, for example:

document.getElementById("edName").required = true;

(Just for completeness.)

reply:

That's becauserequiredin this code is aproperty object, not a string;propertyisNamedNodeMapIts value isAttr代码>object. To get the value of one of these, you need to look at itsvalueproperty. But for boolean properties, the value is irrelevant; the property is either present in the map (true) or not (false).

So ifrequiredis notreflected, you can set it by adding the attribute:

element.setAttribute("required", "");

...Equivalent toelement.required = true. You can clear it by deleting it completely:

element.removeAttribute("required");

...Equivalent toelement.required = false.

But we don't have to do this forrequiredbecause it's already reflected.

    P粉133321839

    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 thereflected properties, I learned the following syntaxerror:

    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

    Youmustpasselement.getAttributeandelement.setAttribute:

    element.getAttribute("foo"); //correct element.setAttribute("foo", "test"); //correct

    This is because the attribute actually contains a specialHtmlAttributeobject:

    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 the attribute value to "true", you are mistakenly setting it to aStringobject instead of theHtmlAttributeobject 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 type language) is:

    HtmlAttribute attribute = new HtmlAttribute(); attribute.value = ""; element.attributes["required"] = attribute;

    Here’s why:

    • getAttribute(name)
    • setAttribute(name, value)

    exist. They are responsible for assigning values to the internal HtmlAttribute objects.

    In addition, it alsoreflects some attributes. This means you have better access to them via 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 youdon'twant to do is incorrectly use the.attributescollection:

    element.attributes.required = true; //WRONG! if (element.attributes.required) {...} //WRONG! element.attributes.required = false; //WRONG!

    Test Case

    This results in testing around the use of therequiredattribute, comparing the value returned via that attribute to the reflected attribute

    document.getElementById("name").required; document.getElementById("name").getAttribute("required");

    result:

    HTML .required .getAttribute("required") ========================== =============== =========================false (Boolean) null (Object)true (Boolean) "" (String)true (Boolean) "" (String)true (Boolean) "required" (String)true (Boolean) "true" (String)true (Boolean) "false" (String)true (Boolean) "0" (String)

    It is an error to attempt to access the.attributescollection directly. It returns an object representing a DOM property:

    edName.attributes["required"] => [object Attr] edName.attributes.required => [object Attr]

    This explains why you should never talk directly to the.attributescollection. You are not manipulating thevalueof the property, you are manipulating the object that represents the property itself.

    How to set required fields?

    What is the correct way to setrequiredon a property? You have two options, either reflected properties or by setting the properties correctly:

    element.setAttribute("required", ""); //Correct element.required = true; //Correct

    Strictly speaking, any other value will "set" the property. However, the definition of theBooleanproperty states that it can only be set to the empty string""to indicatetrue. The following methods canset therequiredBooleanattribute,

    Butdon’t usethem:

    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 have learned that it is an error to try to set the property directly:

    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 toclearrequired fields?

    TryRemoverequiredThe trick when using an attribute is that it's easy to accidentally open it:

    edName.removeAttribute("required"); //Correct edName.required = false; //Correct

    Invalid method:

    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 reflection's.requiredproperty, you can also use any "falsey" value to turn it off and use a true value to turn it on. But for the sake of clarity, stick to right and wrong.

    How tocheck ifisrequired?

    Check whether the attribute exists through the.hasAttribute("required")method:

    if (edName.hasAttribute("required")) { }

    You can also check via theBooleanreflected.requiredproperty:

    if (edName.required) { }
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!