jQuery验证插件-比较两个选择下拉列表的自定义方法

jQuery Validation plugin - Custom method comparing two select dropdowns

本文关键字:两个 选择 下拉列表 自定义方法 插件 验证 比较 jQuery      更新时间:2024-05-07

我有两种选择类型的HTML:

<label for="h_slat_type">Slat Type</label>
<select name="h_slat_type" id="h_slat_type">
                    <option disabled="disabled" selected>Select</option>
                    <option disabled="disabled">---------</option>
                    <option value="1">Type 1</option>
                    <option value="2">Type 2</option>
            </select>
<label for="v_slat_type">Slat Type</label>
<select name="v_slat_type" id="v_slat_type">
                    <option disabled="disabled" selected>Select</option>
                    <option disabled="disabled">---------</option>
                    <option value="1">Type 1</option>
                    <option value="2">Type 2</option>
            </select>

验证失败的条件是当我将h_slat_typev_slat_type都设置为2时。

换句话说,如果:

h_slat_type 1=v_slat_type 1->真实

h_slat_type 2=v_slat_type 1->真实

h_slat_type 1=v_slat_type 2->真实

h_slat_type 2=v_slat_type 2->错误

JS方法:

jQuery.validator.addMethod("typecheck", function(value, element) {
    return ($('#h_slat_type').val() == $('#v_slat_type').val());
}, "Horizontal Type 2 and Vertical Type 2 incompatible!");

在这种情况下,什么会起作用?ty vm。

试试这个:

    if($('#h_slat_type').val() == $('#v_slat_type').val())
       return true;
    else if ($('#h_slat_type').val()==1 && $('#v_slat_type').val()==2)
       return true;
    else if ($('#h_slat_type').val()==2 && $('#v_slat_type').val()==1)
       return true;
    else
       return false;

您可以尝试以下代码:

{
var selection_1 = $('#h_slat_type').val();
var selection_2 = $('#v_slat_type').val();
if(selection_1=='2' && selection_2=='2') return false;
return true;
}