Skip to content
Advertisement

Add class to element based on input value length/state with JavaScript

I’m trying to create the ‘floating labels’ effect for my fields. However, I’m having difficulties because the HTML code is structured in such a way that prevents it from being achieved using only CSS as there is no way to use CSS combinators (>,+,~) and I do not have the ability to change the HTML code.

My code:

JavaScript
JavaScript

But I believe it would be possible if I was able to give the container a CSS class based on the field’s input/state. I would like to give the container the display-floating-label class if the value of the input is greater than 0 ( > 0 ). And maybe when the input is focused as well. Is that possible with JavaScript?

I’ve tried:

JavaScript

But it didn’t work. I’m not very familiar with JavaScript so I would really appreciate if someone could help me out.

Here’s what I’m trying to achieve:

enter image description here

*I can not change the structure of the HTML code, I can only work with what I have.

Advertisement

Answer

Try the below snippet.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement