簡體   English   中英

jQuery的表單驗證與提交按鈕

[英]jquery form validation with submit button

我在我的網站項目上,看來我的jquery函數不起作用。我必須驗證一下:如果用戶輸入<<nom de famille du pere>> ,則必須輸入<<prenom du pere>>也輸入了。這是我的html代碼:

 <div class="form-group"> <div class="col-md-6"> <label class="col-md-4 control-label" for="father">Nom de famille du père </label> <input id="father" name="father" type="text" class="form-control input-md" > </div> </div><br/><br/><br/> <div class="form-group"> <div class="col-md-6"> <label class="col-md-4 control-label" for="ffather">Prénom du père</label> <input id="ffather" name="ffather" type="text" class="form-control input-md"> </div> </div><br/><br/><br/> 

這是我的jquery函數:

 $(document).ready(function() { $('#father').submit(function() { if ($(this)).is(':empty')) { $('#ffather').prop('required',false); } else{ $('#ffather').prop('required',true); }} } 

演示: http : //jsfiddle.net/Lfnrrdfu/1/

您的代碼中有一些錯誤:

$('#father').on('keyup', function () {
    if (!$(this).val()) {
       $('#ffather').prop('required',false);  
    }
    else{
      $('#ffather').prop('required',true);  
    }
    console.log($('#ffather').prop('required'));
});

您不能將Submit事件與輸入一起使用,submit用於表單,可以使用表單,但是必須防止默認值,然后檢查輸入的值。

您正在嘗試在提交表單時設置屬性,這不是正確的方法。 您只應檢查字段是否滿足提交要求。 定義約束應該在標記上。 如果不使用任何自定義表單驗證器,則可以使用HTML約束驗證。 可以在這里找到示例http://www.w3schools.com/js/js_validation.asp

同樣,jQuery Submit事件只能附加到表單元素。 在這里查看https://api.jquery.com/submit/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM