jQuery 有条件地验证选择字段

发布于 2025-01-05 21:18:26 字数 427 浏览 2 评论 0原文

我需要能够根据特定选择字段的内容有条件地要求验证某些字段。例如,我有以下选择:

<select name="new_jobType">
<option value="">Please select</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
</select>

如果选择“选项 4”,我需要包含 5-6 个其他选择字段进行验证。

任何帮助将不胜感激。

I need to be able to conditionally require certain fields to be validated, based on the contents of a specific select field. For example, I have the following select:

<select name="new_jobType">
<option value="">Please select</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
</select>

If 'option 4' is selected, I need to include 5-6 other select fields to be validated.

Any help would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

滿滿的愛 2025-01-12 21:18:26

我可能会这样做:

var validations = new Array();

$('select[name="new_jobType"]').change(function() {
    var thisJob = $(this + " option:selected").val();

    if(thisJob == 4) {
        validations.push("thisJobValidations");
    }
});

只需将需要运行的任何验证例程推送到该验证数组上,然后提交:

for(var i = 0; i < validations.length; i++) {
    eval(validations[i] + "();");
}

您将拥有执行实际验证的函数:

function thisJobValidations() {
    // validation magic happens here
}

eval() for 循环内将根据推送到 validations 数组中的内容执行验证例程。

这样,您就可以根据满足的条件对验证进行分段,并且不必编写一个更容易出错的整体验证函数。

把所有的东西都封装起来!! :-)

I might do something like this:

var validations = new Array();

$('select[name="new_jobType"]').change(function() {
    var thisJob = $(this + " option:selected").val();

    if(thisJob == 4) {
        validations.push("thisJobValidations");
    }
});

Just push any validation routines that need to run onto that validations array, and then on submit:

for(var i = 0; i < validations.length; i++) {
    eval(validations[i] + "();");
}

And you would have function(s) to do the actual validations:

function thisJobValidations() {
    // validation magic happens here
}

The eval() inside the for loop will execute the validation routine(s) based on what had been pushed onto the validations array.

That way you can segment your validations based on what conditions had been met, and you don't have to write one monolithic validation function that would be more error-prone.

Encapsulate all the things!! :-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文