我正在試圖製作一個使用jquery的調查系統。我需要檢測是否有任何輸入值爲空,然後獲取錯誤函數。我做到了,但它只工作一次。如何多次使用我的代碼?檢查多個輸入的空值不會工作
我創造了這個
$(document).ready(function(){
$("body").on("click",".createnew", function(){
if ($(".myinput").val().length !== 0) {
if($('.input').length !== 4){
$(".inputs").append("<div class='input' id='surway_poll'><input type='text' class='myinput' id='hoho' placeholder='Write something!'></div>");
} else {
$(".createnew").remove();
}
} else {
alert("You can not leave it blank input field!");
}
});
});
html,
body {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
font-family: helvetica, arial, sans-serif;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
}
.container {
position:relative;
width:100%;
max-width:500px;
margin:0px auto;
overflow:hidden;
margin-top:100px;
}
.inputs {
position:relative;
width:100%;
overflow:hidden;
}
.input {
position:relative;
width:100%;
overflow:hidden;
margin-bottom:10px;
}
.myinput{
width:100%;
position:relative;
height:35px;
font-size:14px;
padding:10px;
outline:none;
}
*{
box-sizing:border-box;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
}
.createnew{
position:relative;
float:right;
margin-top:10px;
font-size:14px;
font-weight:600;
background-color:red;
color:#ffffff;
padding:8px;
}
.error {
border:1px solid red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="inputs">
<div class="input" id="surway_poll">
<input type="text" class="myinput" id="hoho" placeholder="Write something!">
</div>
</div>
<div class="createnew">Create New Input</div>
</div>
在本演示中,你可以看到創建一個新的輸入按鈕。所以如果你點擊它,你會得到警報。因爲你沒有從輸入中寫入任何文本。但是,如果您創建第二個輸入,而不是空白,那麼警報在當時不起作用。我在這裏錯過的任何人都可以告訴我?
啊,我怎麼能錯過它。謝謝@trincot。 – Azzo
如果最後一個輸入不是空的,但其上面的一些仍然是空的,這將失敗。 – Dij
@Dij,用戶可以隨時清除以前非空的輸入,即使在添加一行後也是如此,所以無論如何都不能阻止。我添加了一個變體來檢查所有的輸入,但在我看來,這是由於上述原因矯枉過正。 – trincot