Home > Software engineering >  How to create input tag with js without it being ":valid" for css purpose
How to create input tag with js without it being ":valid" for css purpose

Time:11-30

I have super simple input witch I have written in html/css and it works as it should but when I decided to write function in js to automate process of creating multiple inputs I had a problem. Input that I created with js is already valid(from css ":valid" standpoint) and it is not when i write it in just html/css. I need it to be invalid from the start when it doses not have any content in it and then when i write something in it, it needs to become valid. Here is CodePen with the code. So to sum up I need to know how to make js version same as html/css version.

I have tried both .setCustomValidity(0) and .value = '' the problem with first is that input stays :invalid even when I type something in to the input. Second solution dose not work at all.

CodePudding user response:

The HTML input is invalid because it is required (and empty).

The example JavaScript code does not set the required attribute on the input.

const input = document.createElement('input')
input.required = true;
document.body.appendChild(input);
console.log(document.querySelector(':invalid'));

Please don’t forget to provide a real <label> for the input. It’s very important to make the form accessible with assistive technology for users with disabilities.

What is currently named placeholder is actually a label. Material Design calls it a floating label, because it will be floating above the input once it has a value.

const placeholder = document.createElement('label');
…
input.id = 'theinput';
placeholder.setAttribute('for', 'theinput');
  • Related