检查是否以动态形式检查复选框是否有效

时间:2013-11-25 17:18:38

标签: javascript jquery

我正在开发一个网页,可以动态添加复选框。我检查表单是否正确构建,并在提交表单时由php文件正确处理。提交表单时,我的验证功能会检查是否选中了某些复选框,但此部分不起作用。当选中复选框时,使用'is(":checked")'始终返回false。我强烈怀疑原因是我在表单提交代码中查看控制台的输出时错误地定义了选择器($('#approved_agreement['+ i +']'))(见下文):输出显示奇怪(对我来说)相同的ID(approved_agreement) %5B%5D)但是作为正确的元素数组传递给$_POST

如何解决这个问题?如果可能的话,我想保留复选框ID定义(所以我不需要重写php代码)。

//related form building code
form += '<td> <input type="checkbox" id="approved_agreement[]" name="approved_agreement[]" value="'+ msg[i].name +'"> </td></tr>';
//code for appending form to wrapper

//related validation code
for(var i=0;i<msg.nrofagreements;i++){
        console.log('VALIDATE FORM agreement id: '+'#approved_agreement['+ i +']'); 
        console.log('VALIDATE FORM agreement len: '+ $("#approved_agreement["+ i +"]").length); //show value 0 indicating the element does not exist
        console.log('VALIDATE FORM agreement checked: '+$("#approved_agreement["+ i +"]").is(":checked")); //always shows value false 
         //approved_agreement[]
        if($('#approved_agreement['+ i +']').is(':checked')){
           //some validation code here...
        }//if
}//for

//related code within form submit function
$("#FormAgreementsConfirm").submit(function(event){
    var dataAjax = $( this ).serialize(); //does not work, but when copying the string from the console in line below it odes work.
    console.log('SUBMITTED FORM: '+ dataAjax  ); //shows (when checking the checboxes): approved_agreement%5B%5D=SolarX_10&approved_agreement%5B%5D=SolarX_11
}

0 个答案:

没有答案