我有代码允许用户在一个人 TYPEA
和 TYPEB
的两个选项之间进行选择。
SELECT PERSON - { TYPEA, TYPEB }
根据选择,它显示:
TYPEA - { TYPEA WITH ID, TYPEA WITHOUT ID }
TYPEB - { TYPEB WITH ID, TYPEB WITHOUT ID }
它正在处理这个:
html:
<div id="person-A-withID" class="persons" style="display:none"></div>
<div id="person-A-withoutID" class="persons" style="display:none"></div>
<div id="person-B-withID" class="persons" style="display:none"></div>
<div id="person-B-withoutID" class="persons" style="display:none"></div>
jQuery:
$(function () {
$('#has_id').show();
$('#select_person').change(function () {
$('.persons').hide();
if ($('#select_person').val() == 'typeA') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type A--').appendTo("#has_id");
$("<option/>").val('person-A-withID').text('person-A-withID').appendTo("#has_id");
$("<option/>").val('person-A-withoutID').text('person-A-withoutID').appendTo("#has_id");
}
if ($('#select_person').val() == 'typeB') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type B--').appendTo("#has_id");
$("<option/>").val('person-B-withID').text('person-B-withID').appendTo("#has_id");
$("<option/>").val('person-B-withoutID').text('person-B-withoutID').appendTo("#has_id");
}
});
$('#has_id').change(function () {
$('.persons').hide();
$('#' + $(this).val()).show();
});
});
我有一个函数来验证值是否为空或等于 0,代码如下:
function validate(id, msg) {
//search object
var obj = $('#' + id);
if(obj.val() == '0' || obj.val() == ''){
//append error to particular div called #id__field_box
$("#" + id + "_field_box .form-error").html(msg)
return true;
}
return false;
}
我在这样的验证函数中调用它:
var validation = function(){
var err = 0;
err += validate('select_person', "select person.");
//err += validate($('#select_person:first-child').attr('has_id'), "Select wether it has ID or not.");
//err += validate('has_id', "Select wether it has ID or not.");
if(err == 0){
//continue
}else{
//stop
}
};
现在,问题是我无法验证 has_id
部分,我只能验证第一个部分。我如何使用它来搜索 has_id
?
最佳答案
在您的示例中,没有 ID 为“selector_persona”的元素。这会阻止您的第二个验证函数工作。通过将您要验证的内容的 ID ('has_id') 传递给它,它会引用该对象并检查以确保它具有值。
选择一个人,将第二个选择保留为“--选择类型 A--”,然后单击“确定”。它返回你的错误。 http://jsfiddle.net/zyglobe/LEfbX/131/
var validation = function(){
var err = 0;
err += validate('select_person', "select person.");
err += validate('has_id', "Select whether it has an ID or not.");
if(err == 0){
alert('continue');
} else{
alert('error: ');
}
};
你也可以检查这部分:
$('#select_person:first-child').attr('has_id')
您正在尝试查找名称为 has_id 的属性,它适用于如下情况:
<select has_id="some_value" />
我想你的意思是选择 attr('id') 它将返回 'has_id' 的值:
<select id="has_id" />
关于javascript - 根据条件验证动态创建的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15933559/