1

I have a code like this:

<div><input type="text" value=""></div>

How do I check with JS or jQuery if input contain any data (even from localstorage or browser cache) on load and add class to parent div if not empty?

3
  • Reading the documentation is always useful. Commented Sep 27, 2016 at 17:27
  • there is no direct connection between localStorage and an <input> element Commented Sep 27, 2016 at 17:31
  • Thanks, I'm just not very experienced in JS, that's why asked for help. Commented Sep 27, 2016 at 17:39

3 Answers 3

2

Try this

//trim() is used to remove extra spaces in your input value
if($('#ver_input').val().trim() != ''){
    $(this).parent().addClass('any-class');
}

html:

<div><input type="text" value="" id="ver_input"></div>
Sign up to request clarification or add additional context in comments.

Comments

2

To check if the value of an input is not empty, use the following:

if($("input").val()) { ... }

If there are multiple inputs you may want to put an id on this input, but this code works if there is just one input.

Comments

1
  var input = document.querySelector('input');
  var yourDiv = document.querySelector('div');


  if(input.value === ''){
    yourDiv.classList.add("foo");
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.