对下拉菜单中的特定选项执行onclick验证

performing onclick validation on particular option in dropdown menu

本文关键字:选项 执行 onclick 验证 下拉菜单      更新时间:2023-09-26

我有一个下拉菜单,里面有大约五个选项和一个将其作为表单提交的按钮。我想知道是否可以在onclick中执行验证,这样无论选择什么选项,都可以进行不同的验证。

因此,例如,如果用户选择选项Milk并单击按钮,onclick将使用方法A进行验证,其中,就像用户选择选项Cheese并单击按钮一样,onclick将使用方法B进行验证。

目前,我只能让onclick对所有选定的选项使用单个验证。

谢谢你的帮助。

在您的函数中点击检查您的选择值

function methodA(){
    //
}
function methodB(){
    //
}
function doOnClick(){
    switch($('your-select').val()){
        case 0 :
           methodA();
        break; 
        case 1 :
           methodB();
        break; 
    }
}

http://jsfiddle.net/adYtd/

获取select选项的值,然后将其用作保存验证函数的对象的键。

var Validation_Functions = {
    1: function(x){alert("1"+x);},
    2: function(x){alert("2"+x);},
    3: function(x){alert("3"+x);},
    4: function(x){alert("4"+x);},
}
$("#btn").on("click", function() {
    var val = $("#sel").val();
    Validation_Functions[val](" test");
});

HTML:

<form id="formid">
    <select id="selectid">
        <option value="milk"> Milk </option>
        <option value="sugar"> Sugar</option>
    </select>
</form>

JS:

var validationRules = {
    'milk': function(){
        // validate
        return false;
    },
    'sugar': function(){
        // validate
        return true;
    }
}
var form = document.getElementById('formid');
var select = document.getElementById('selectid');

select.addEventListener('change', function(){
    var value = this.options[this.selectedIndex].value;
    form.valid = validationRules[value]();
});

form.addEventListener('submit', function(){
    return this.valid;
});