2

我有代码允许用户在一个人和 2 个选项之间进行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

这是一个小提琴,请看一下

4

1 回答 1

1

在您的示例中,没有 id 为“selector_persona”的元素。这会阻止您的第二个验证功能工作。通过将您要验证的 id ('has_id') 传递给它,它会引用该对象并检查以确保它具有一个值。

选择一个人,将第二个选项保留为“--Choose Type 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" />

我认为您的意思是选择将返回“has_id”值的 attr('id'):

<select id="has_id" />
于 2013-04-25T15:00:49.587 回答