添加复选框验证

时间:2016-10-10 14:21:16

标签: javascript checkbox

目前正在验证日期和年份,但我想在列表中添加一个复选框。

表格代码:

var html = '';
    html += '<div class="ac-overlay"></div>';
    html += '<div class="ac-container">';
    html += '<h2>' + settings.title + '</h2>';
    html += '<p>' + copy.replace('[21]','<strong>'+settings.minAge+'</strong>'); + '</p>';
    html += '<div class="errors"></div>';
    html += '<div class="fields"><select class="month">';for(var i=0;i<months.length;i++){
    html += '<option value="'+i+'">'+months[i]+'</option>'}
    html += '</select>';
    html += '<input class="day" maxlength="2" placeholder="01" />';
    html += '<input class="year" maxlength="4" placeholder="2016"/>';
    html +="<br><br>";
    html +='<p><input class="smoker" type="checkbox"/>Please verify that you are a smoker.</p>';
    html +="<br>";
    html += '<button>Submit</button></div></div>';

验证脚本:

 validate : function(){
 _this.errors = [];
 if (/^([0-9]|[12]\d|3[0-1])$/.test(_this.day) === false) {
 _this.errors.push('Day is invalid or empty');
 };
 if (/^(19|20)\d{2}$/.test(_this.year) === false) {
 _this.errors.push('Year is invalid or empty');
 };
 _this.clearErrors();
 _this.displayErrors();
 return _this.errors.length < 1;
 },

我使用以下代码玩了一下但是缺少了一些东西:

if ("Not sure what to enter here to validate the checkbox.".test(_this.smoker) === false) {
_this.errors.push('You have not selected if you are a smoker');
};

1 个答案:

答案 0 :(得分:0)

有点解决方法,但最终更改了Checkbox以启用和禁用验证按钮。

$(document).ready(function(){
                $('#isAgeSelected').change(function(){
                    if(this.checked)
                    $('#autoUpdate').fadeIn('slow');
                    else
                    $('#autoUpdate').fadeOut('slow');
                });
                });

                html +="<br><br>";
                html += '<p><input type="checkbox" id="isAgeSelected"/> Please verify the date above is correct.';
                html += '<div id="autoUpdate" class="autoUpdate" style="display:none"><button>Submit</button></div>';
                html += '</div></div>';

了解它的工作原理:http://jsfiddle.net/3WEVr/1135/