嗨,大家好我是jquery的新手我想在我的表單上放置一個檢查,當我提交表單的函數時,只需檢查表單的所有字段,如果任何字段爲空只顯示一個錯誤,請填寫所有內容 這裏是我的代碼:使用jquery檢查表單的所有空字段
function validate() {
//get all inputs of the form in array
var inputs = $('#form :input');
var k = 0;
inputs.each(function() {
if ($(this).val() == '') {
k = 1;
}
});
if (k == 1) {
alert('please fill all fields');
} else {
alert('submitted successfully');
}
}
function postvalue(id) {
$('#value').val(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal" id="form">
<fieldset>
<!-- Form Name -->
<legend>Form Name</legend>
<div class="form-group">
<input type="hidden" value="" id="value" />
<label class="col-md-4 control-label">Double Button</label>
<div class="col-md-8">
<button type="button" onclick="postvalue(1)">click</button>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="selectbasic">Select Basic</label>
<div class="col-md-8">
<select id="selectbasic" name="selectbasic" class="form-control valid">
<option value="">select option</option>
<option value="2">Option one</option>
</select>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-4 control-label">Double Button</label>
<div class="col-md-8">
<input type="number" class="valid" />
</div>
</div>
<input type="submit" value="submit" onclick="validate()" />
</fieldset>
</form>
這是什麼問題? – adeneo
總是說,請填寫所有字段,即使我填寫所有字段 – Farid
哦,我明白了。這是因爲':input'選擇隱藏的輸入,按鈕,所有元素和所有這些元素都沒有值,因此失敗。 – adeneo