繁体   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