2016-08-29 23 views
0

我有一个窗体,每个复选框有多个复选框字段和相应的注释字段。我动态地创建这些字段。例如,复选框字段tag1将对应于comments1。当复选框被选中时,我不想要求评论。当它没有被检查时,我想要求评论。复选框更改事件触发另一个字段是必需的

有时,根据用户的上次输入预填充字段。换句话说,复选框可能已经在页面加载时被检查,或者可能不是。我有逻辑设置建立相应的注释字段为要求或不需要基于此。

一切似乎都在工作,除了一个。当我选中该复选框并取消选中该复选框时,表单允许我提交没有评论。以下是我所尝试过的。

$(document).on('change', 'input[type=checkbox]', function() { 
    var checkbox = $(this), 
    otherInput = $('#comments' + this.id.replace('tag', '')); 


    otherInput.removeProp('required', !checkbox.is(':checked')); 
    if (!checkbox.not(':checked')){ 
    otherInput.prop('required',true); 
    } 
}); 

--------------------第二次尝试

$(document).on('change', 'input[type=checkbox]', function() { 
    var checkbox = $(this), 
    otherInput = $('#comments' + this.id.replace('tag', '')); 

    otherInput.prop('required', !checkbox.not(':checked')); 
    otherInput.removeProp('required', !checkbox.is(':checked')); 

}); 

的这两种解决相同的情况下,除了所述一个,如上所述。请指教。

+0

'otherInput.removeProp('required',!checkbox.is(':checked'));'在第二个例子中是什么意思? – guest271314

+0

@ guest271314当用户选中复选框时,它将从相应的注释字段中删除所需的属性 –

+0

是的,尽管前一行'otherInput.prop('required',!checkbox.not(':checked'));'实现了这个,是吗?你可以创建一个jsfiddle来演示问题吗? – guest271314

回答

1

只需拨动基于复选框状态 '所需的' 属性

$(document).on('change', 'input[type=checkbox]', function() { 
    var checkbox = $(this), 
    otherInput = $('#comments' + this.id.replace('tag', '')); 

    otherInput.prop('required', !checkbox.is(':checked')); 

}); 

看到这个JSFiddle

+0

好的答案+1如果可以的话,最好提供一个概念演示,*使用[jsFiddle](http://jsfiddle.net)或在编辑器中按Ctrl + M并创建堆栈片段例。* – gibberish

0

当 “提交” 按钮被按下,就开始验证:

伪代码:

onSubmitPressed: function(){ 
    if(checkbox is checked){ 
     // alert user field is required; 
     return false; 
    }else{ 
     return true; 
    } 
0

看起来我有一些不好的语法,但它并没有抛出一个错误。我改变了我的第一次尝试:

$(document).on('change', 'input[type=checkbox]', function() { 
    var checkbox = $(this), 
    otherInput = $('#comments' + this.id.replace('tag', '')); 

    otherInput.removeProp('required', !checkbox.is(':checked')); 

    if ($(this).is(':not(:checked)')){ 
    otherInput.prop('required',true); 
    console.log('working'); 
    } 
}); 

这就是现在添加和删除基于复选框所需的属性被检查或不检查。

相关问题