如何在加载时检查输入是否为空?

时间:2016-09-27 17:23:59

标签: javascript jquery html

我有这样的代码:

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

如果输入在加载时包含任何数据(甚至来自localstorage或浏览器缓存),我如何检查JS或jQuery,如果不为空,则将类添加到父div?

3 个答案:

答案 0 :(得分:2)

试试这个

//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>

答案 1 :(得分:2)

要检查输入的值是否为空,请使用以下命令:

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

如果有多个输入,您可能想在此输入上放置一个id,但如果只有一个输入,则此代码有效。

答案 2 :(得分:1)

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


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