简体   繁体   中英

My button is working even though the input is set to "required"

I created a Form with an Input as a Text type and also a Button to execute a Javascript code.

<input required type="text" id="bNum" value="" name="bNum" size="6" maxlength="6" placeholder="Badge Number" onkeyup="this.value = this.value.toUpperCase();">

<button onclick=" verify();return false;">Verify</button>

function verify () {
  var bno = document.getElementById("bNum").value;

  switch (bno) {
    case "AJC8":
      alert("You are a Verified member!")
      break;
        
    case "AJB0":
      alert("You are a Verified member!")
      break;
    
    default:
      alert("You are Not a Verified member!")
      break;
  }
}

If I click the button the function executes it and does not show that the field is required.

You are mixing in multiple concepts and behaviors, and your expectations don't match the current specs for these HTML attributes.

This is what the MDN says for the required attribute of the<input> element:

required

required is a Boolean attribute which, if present, indicates that the user must specify a value for the input before the owning form can be submitted . The required attribute is supported by text, search, url, tel, email, date, month, week, time, datetime-local, number, password, checkbox, radio, and file inputs.

Emphasis added by me. Note that required attribute will only block a form's submission. Meaning that it would only present the action of submitting a <form> element, which is not what you are doing here.

required simply doesn't block other interactions, although you could rely on it to implement your own blocking logic in your JS code and control the interaction with your elements.

For instance, you could add an onClick listener on the button and check whether your input is marked as "required" and has an empty value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM