验证jQuery中的下拉列表 [英] Validate dropdown list in jquery

查看:91
本文介绍了验证jQuery中的下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在html中有一个下拉菜单,我想使用jquery对其进行验证.

I have one dropdown in html and i want to validate it using jquery.

 Please select your rating * :
    <select id="myDropdown">
    <option value="">-Please Select-</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
    </select>

我的Jquery代码就像

My Jquery code is like

if ($('#myDropdown option:selected').length == 0)
    {
      alert("Please select anyone");
    }

我需要的是,如果未选择任何值,并且该值仍保持为-Please Select-,并且如果用户按下Submit(提交)按钮,则需要显示警报或任何适当的消息 请帮助

What I need is if any value is not selected and it remains like -Please Select- and if the user press submit button, then an alert or any appropriate message needs to be displayed Please help

推荐答案

mydropdown = $('#myDropdown');
if (mydropdown.length == 0 || $(mydropdown).val() == "")
{
    alert("Please select anyone");
}

请参阅下面的注释.另外,您不需要option:selected(根据Sly的原始答案).

See Note below. Also, you don't need the option:selected (as per Sly's original answer).

在此小提琴上,尝试选择另一个值,然后尝试选择-Please Select-选项.您将看到alert().

On this fiddle, try selecting another value, then try to select the -Please Select- option. You will see the alert().

http://jsfiddle.net/userdude/aS2AM/

编辑

注意:长度测试什么都不做,因为它将始终报告1,因为始终选择至少一个选项(并且选择器始终选择至少一个选项,除非选择具有没有选择).我已在此更新中删除了该提琴和下面的代码:

NOTE: The length test is doing nothing, since it will always report 1, as at least one option is always selected (and your selector is always selecting at least one option, unless the select has no options). I have removed that in this update to the fiddle and code below:

http://jsfiddle.net/userdude/LdN6c/3/

您没有捕获表单提交事件.

You're not capturing the form submit event.

$(document).ready(function() {
    $('#myForm').submit(function(e){ // <<< This selector needs to point to your form.
        if ($('#myDropdown').val() == "") {
            alert("Please select anyone");
            e.preventDefault();
            return false;
        }
    });
});

请注意#myForm需要选择包含所选元素的实际表单元素.

Note the #myForm needs to select your actual form element that contains the selected element.

在此处查看实际操作: http://jsfiddle.net/userdude/LdN6c/1/

See in action here: http://jsfiddle.net/userdude/LdN6c/1/

这篇关于验证jQuery中的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆