简体   繁体   English

表单验证中的更改事件

[英]Change event on Form validation

I am working on the following jQuery form validation script. 我正在研究以下jQuery表单验证脚本。

I am looking to validate that certain input fields are populated before the submit button is clickable. 我想验证单击提交按钮之前是否已填充某些输入字段。 I seem to be having an issue with the second condition within my validateFileInput function 我的validateFileInput函数中的第二个条件似乎有问题

/* Validate File Size */
var validateFileInput = function() {
  if ($('#fileField')[0].files.length > 0 || $('#defImage').val().length > 0 )   {
    return true;
   }
 }                   

var validate = function(){
  if ($('#campaign_name').val().length   >   0   &&
      $('#headline_area').val().length  >   0   &&
      $('#description_area').val().length  >   0 &&
      validateFileInput()  ) {
      $("input[type=submit]").prop("disabled", false);
  }
  else {
    $("input[type=submit]").prop("disabled", true);
  }
}

$(document).ready(function () {
 validate();
  $('#new_campaign').on( 'change', ':input', function (e){
    e.preventDefault();
    validate();
    console.log('I just validated');   
 });
});

So it seems that this line is the issue as when the condition is met the submit button is still unclickable: 因此,似乎这行是问题所在,因为当满足条件时,提交按钮仍然不可单击:

$('#defImage').val().length > 0

If I run it in the console after adding a file it outputs to true, so I'm not sure as to why this will not work. 如果我在添加文件后在控制台中运行它,则输出为true,因此我不确定为什么它不起作用。

Edit 编辑

The html for the second file field looks like so: 第二个文件字段的html如下所示:

<a data-remote="true" data-target=".our-images" data-toggle="modal" href="/default_images" id="image-default-button">Use one of ours</a>   
<input id="defImage" name="campaign[default_image_id]" type="hidden" />

I am using an Ajax request to get the image and then passing the id of the image to the hidden field #defImage, which will then give me 我正在使用Ajax请求来获取图像,然后将图像的ID传递给隐藏字段#defImage,这将给我

<input id="defImage" name="campaign[default_image_id]" type="hidden" value="3" />

Am I handling this wrong with the validation? 我在验证时会处理这个错误吗?

I have created a jsfiddle but this all works when the input type is set to file. 我创建了一个jsfiddle,但是当输入类型设置为file时,这一切都可以工作。

Your function returns true if there's a file, but undefined when the condition is false , so it fails. 如果有文件,则函数返回true ,但条件为false时函数undefined ,因此失败。

Try to change your 尝试改变你的

var validateFileInput = function() {
  if ($('#fileField')[0].files.length > 0 || $('#defImage').val().length > 0 )   {
    return true;
   }
 }  

to : 至 :

var validateFileInput = function() {
  return ($('#fileField')[0].files.length > 0 || $('#defImage').val().length > 0 );
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM