Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading