[英]validation of select box in javascript
您好,我開發了一個表單,其中有輸入框和選擇框。 我想對選擇框和輸入框進行驗證。 我只能對輸入框進行驗證。我無法對帶有輸入框的選擇框進行驗證。
$(document).ready(function(){ $("#myform").validate(); });
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script> <form action="#" id="myform"> <label class="label1 col-md-4">Enter Template Name <span class="required"> * </span> </label> <input id="templateName" type="text" data-required="1" class="form-control" /> </br> <label class="label1 col-md-4">Enter Admission Year <span class="required"> * </span> </label> <input id="admissionYear" type="text" data-required="1" maxlength="4" /> </br> <label class="label1 col-md-4">Select the type of eligibility <span class="required"> * </span> </label> <select id="reportsSelect" class="form-control" data-placeholder="Select" tabindex="1"> <option value="0">Choose</option> <option value="overall">Overall</option> <option value="specific">Specific subject</option> </select> </br> <button type="button">Submit</button> </form>
這里有幾個“問題”。
您的標簽不會引用它們所屬的輸入,要么通過將輸入包含在其中,要么使用for
屬性引用相應輸入的ID。
<select>
上的placeholder
是沒有意義的
您應該使用required
,而不是data-required="1"
-這使瀏覽器無需任何代碼即可進行驗證。 如果您有任何jQuery驗證,請將其刪除。 這是2017年, 您不需要它 :p
對於“無值”的選項select
應<option value="">
然后,可以將required
添加到<select>
以要求用戶選擇一個不為空的值。
使用<input type="submit" value="Submit" />
或<button type="submit">Submit</button>
,而不是<button type="button">
我假設您有一個jQuery事件處理程序來處理表單。 如果使用required
屬性(瀏覽器本機驗證),則可以僅偵聽表單上的.on('submit')
事件-如果無效則不會觸發。
$(document).ready(function(){ $("#myform").validate(); });
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script> <form action="#" id="myform"> <label class="label1 col-md-4">Enter Template Name <span class="required"> * </span> </label> <input id="templateName" type="text" data-required="1" class="form-control" /> </br> <label class="label1 col-md-4">Enter Admission Year <span class="required"> </span> </label> <input id="admissionYear" type="text" data-required="1" maxlength="4" /> </br> <label class="label1 col-md-4">Select the type of eligibility <span class="required"> * </span> </label> <select id="reportsSelect" class="form-control" data-placeholder="Select" tabindex="1"> <option value="0">Choose</option> <option value="overall">Overall</option> <option value="specific">Specific subject</option> </select> </br> <button type="button">Submit</button> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.