Home > database >  how to make html input required using JavaScript?
how to make html input required using JavaScript?

Time:07-18

Could you tell me how to achieve html input: <input id="blablabla" required> using javascript

all web answers i have found suggest to write something like:

input.setAttribute('required','true');
input.setAttribute('required','');
input.required='true'

but them all give me something like:

<input id="blablabla" required=''>

or

<input id="blablabla" required='true >

and they doesn't work

Only html that works is <input id="blablabla" required>

Could you help me ?

Thanks

CodePudding user response:

I found your example as well as the other answers working perfectly.
Are you sure you did the right thing? Also you can put like this, it will work too!

myInput.setAttribute('required', 'required');

Example code: Please click Add required and then click Submit

function addRequired() {
  const myInput = document.getElementById('inputText');
  myInput.setAttribute('required', 'required');
  alert('Input has been added required!');
}

function removeRequired() {
  const myInput = document.getElementById('inputText');
  myInput.removeAttribute('required');
  alert('Input has been removed required!');
}
<form>
  <input id="inputText" type="text">
  <button type="button" onclick="addRequired()">Add required</button>
  <button type="button" onclick="removeRequired()">Remove required</button>
  <button>Submit</button>
</form>

CodePudding user response:

You can do this in any of the following ways:

const myInput = document.getElementById('blablabla');

myInput.required = true // Method 1
myInput.setAttribute('required', true); // Method 2

To get something like <input id="blablabla" required> you have to use the first method

If you're looking for the typical asterisk to appear, that's something you have to add manually, with JS or CSS. But if you check the attributes of the element (by inspecting the HTML of the page) you can see that the required attribute has been added.

  • Related