Check if input field contains @ character?

2019-09-21 09:30发布

问题:

Im trying to check if my input field contains an @ sign in it

so here is what i have and its not working:

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

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

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

Any ideas?

回答1:

:contains() returns a jQuery object matching the criteria. It does not match value.

Use indexOf() over .val(),

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

Also, in your else{}, use .val() as text() does not set any value.

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

But I'd suggest you use another element say <span id="emailError">

Updated Fiddle



回答2:

Try this: http://jsfiddle.net/xJtAV/71/. The string function indexOf() will search any string for whatever you'd like and return the index of the first character of the first occurence...

String indexOf() docs: 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>