检查value是否为空javascript


Check if value is empty javascript

提交后,我希望将用户重定向到url中输入值的不同页面。现在,当没有值时,我希望它什么都不做(返回false)。我该怎么做呢?

我的当前代码:

<form action="" method="post" class="searchInput">
    <input type="text" placeholder="Search anything you want..." name="search" id="search" />
    <button name="btnsearch" id="btnsearch" onclick=" window.location = '<?php echo base_url("index.php/search/index")?>/'+document.getElementById('search').value; return false;">
        Search</button>
</form>

有两种方法可以做到这一点。使用JavaScript:

function validateForm() {
    var x = document.forms["myForm"]["nameField"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="nameField">
<input type="submit" value="Submit">
</form>

或者你可以使用HTML5 required属性:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>HTML 5 Form Validation</title>
</head>
<body>
<form action="">
  Username: <input type="text" name="username" required>
  <input type="submit">
</form>
</body>
</html>

现在就看你了!: D

可以使用HTML required属性来实现。它看起来比用javascript处理要好。就像这样:

http://jsbin.com/xumaxilowo/1/edit?html、css、输出

<form action="">
  Username: <input type="text" name="usrname" required>
  <input type="submit">
</form>

这是JS的解决方案,没有帖子将发生在服务器上。(但这段代码需要在PHP文件中)

<form action="" method="post" class="searchInput">
  <input type="text" placeholder="Search anything you want..." name="search" id="search" />
  <button name="btnsearch"
          id="btnsearch" 
          type="button"
          onclick="redirect();"
  >Search</button>
</form>

这里是js

function redirect() {
  var value = document.getElementById('search').value;
  if (value !== '') {
    window.location = '<?php echo base_url("index.php/search/index")?>/' +
                      document.getElementById('search').value;
  }
}

如果你今年正在寻找答案,你可以使用注意:如果数组为空,则返回true,对于这种特殊的边缘情况,您总是可以检查array.length;

return new Boolean(array) && array.length > 0;

更多信息请查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean