2015-04-06 174 views
0

我在我的網站項目,似乎我的jQuery功能不起作用 。我必須驗證這一點:如果用戶輸入<<nom de famille du pere>><<prenom du pere>>也必須輸入too.This是我的html代碼:提交按鈕的jQuery表單驗證

<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')) { 
 
\t $('#ffather').prop('required',false); 
 
\t 
 
\t 
 
} 
 
else{ 
 
\t $('#ffather').prop('required',true); 
 
\t 
 
\t 
 
}} }

+2

如何提交輸入? – adeneo

+1

在窗體上設置'.submit()'處理程序,而不是輸入;或者在輸入 – Plato

+0

上使用'.change()'或'.keyup()',我忘記將表單頭放在代碼中,並且我也有一個提交按鈕 – user3430205

回答

1

DEMO: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')); 
}); 

您不能使用輸入提交事件,是提交一個表單,您可以使用表單,但你必須防止默認值,然後檢查輸入的值。

1

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

同樣,jQuery提交事件只能附加到表單元素。點擊此處https://api.jquery.com/submit/