【问题标题】:Check if input field contains @ character?检查输入字段是否包含@字符?
【发布时间】:2015-05-20 16:12:34
【问题描述】:

我正在尝试检查我的输入字段是否包含 @ 符号

所以这就是我所拥有的,但它不起作用:

$( "#Button" ).click(function() {
    if ($('#email:contains("@")')) {

    } else { 
        $('#email').text('Wrong');
    }
});

http://jsfiddle.net/xJtAV/70/

有什么想法吗?

【问题讨论】:

标签: javascript jquery validation input


【解决方案1】:

:contains() 返回一个匹配条件的 jQuery 对象。它与值不匹配。

.val() 上使用indexOf()

if ($('#email').val().indexOf('@') > -1) {

另外,在你的else{} 中,使用.val() 因为 text() 没有设置任何值。

$('#email').val('Wrong');

但我建议你使用另一个元素,比如 <span id="emailError">

Updated Fiddle

【讨论】:

    【解决方案2】:

    试试这个:http://jsfiddle.net/xJtAV/71/。字符串函数indexOf() 将搜索任何你想要的字符串并返回第一次出现的第一个字符的索引...

    字符串 indexOf() 文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

    JS

    $( "#Button" ).click(function() {
    
        if ($('#email').val().indexOf('@') >= 0) {
           $('#email').val('Yes! It contains an "@" symbol!');
        } else { 
            $('#email').val('No :( No "@" symbol');
        }
    
    });
    

    HTML

    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <input id="email" name="email" class="email" type="text" />
    <br><br>
    
    <div id="Button" style="height:100px; width: 150px; background-color: #000;">
    </div>
    

    【讨论】:

    • 太棒了,非常适合我需要以相反的方式检查它!我需要检查输入字段中是否没有 px,如果有,请添加它。所以我只是把 >= 尊崇为
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 2020-07-12
    • 2021-08-18
    • 2017-09-09
    • 1970-01-01
    相关资源
    最近更新 更多