如果仅打印声明,无论如何都可以度过愉快的一天

时间:2019-04-02 16:36:14

标签: javascript jquery

如果没有文本,它应该发出警报,请输入有效的输入,但是即使没有输入,它也会继续发送第二部分

<script>
    $(document).ready(() => {
        const input = $("#input");
        $(".btn").click(function () {
            if (input.val()) {
                alert("please enter a valid number");
            } else {
                alert("have a nice day");
            }
            console.log(input)

        });
    })
</script>

<body>
    <h1>Weight tracker</h1>
    <h2>please enter your weight</h2>
    <div class="row">
        <form class=" form col s12">
            <div class="row">
                <div class="input-field col s6">
                    <input id="input input_text" type="text" data-length="10" />
                    <a class=" btn waves-effect waves-light btn-small"><i class="material-icons right"></i>submit</a>
                </div>
            </div>
        </form>
    </div>

2 个答案:

答案 0 :(得分:1)

使用input.val() == " "验证输入的值是否等于空格。如果要检查输入是否为空,请尝试:


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(() => {
  const input = $("#input");
  $(".btn").click(function () {
    if (!input.val()) {
      alert("please enter a valid number");
    } else {
      alert("have a nice day");
    }
  });
});
</script>

<body>
<h1>Weight tracker</h1>
<h2>please enter your weight</h2>
<div class="row">
  <form class=" form col s12">
    <div class="row">
      <div class="input-field col s6">
        <input id="input" type="text" data-length="10" />
        <a class="btn waves-effect waves-light btn-small"><i class="material-icons right"></i>submit</a>
      </div>
    </div>
  </form>
</div>
</body>

还尝试添加<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(() => { const input = $("#input"); $(".btn").click(function () { if (!input.val()) { alert("please enter a valid number"); } else { alert("have a nice day"); } }); }); </script> <body> <h1>Weight tracker</h1> <h2>please enter your weight</h2> <div class="row"> <form class=" form col s12"> <div class="row"> <div class="input-field col s6"> <input id="input" type="text" data-length="10" /> <a class="btn waves-effect waves-light btn-small"><i class="material-icons right"></i>submit</a> </div> </div> </form> </div> </body>方法来转义空格,以防万一您想确保它算作空白

.trim()

注意:对于具有!input.val().trim()的子元素,您不能有多个ID。 id属性必须具有单个值

答案 1 :(得分:0)

这表明代码可以正常工作,用" "代替"",空字符串而不是空格:

 const input = $("#input");
$(".btn").click(function () {
    if (input.val() == "") {
        alert("please enter a valid number");
    } else {
        alert("have a nice day");
    }
    // console.log(input)

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input id = "input" type="text"></input>
<button class = "btn">Try</button>