Skip to content Skip to sidebar Skip to footer

Check If Input Fields Contains Certain Text

I'm trying to find if what the user typing in to an input field contain certain text - I've kinda got it works, but only working for an exact match as opposed to a partial match. I

Solution 1:

Checking if a string contains a substring is pretty easily done by taking haystack.indexOf(needle) and checking against -1 (not found).

if ($(".email").val().indexOf("@nyu.edu") !== -1) {
    // contains
} else {
    // does not contain
}

There is a function in the ES6 draft which you may find more natural, called includes

You can add support for ES6'sString.prototype.includes like this

if (!String.prototype.includes) {
    String.prototype.includes = function (needle, pos) {
        returnthis.indexOf(needle, pos || 0) !== -1;
    };
}

"foobar".includes('foo'); // true

Solution 2:

Working Ex:

http://codepen.io/anon/pen/XJKMjo

$('.email').keyup(function() {
    var exp = /@nyu\.edu$/; // reg exvar input = $(this).val(); // email inputvar matches = exp.test(input); // boolean// changes to hidden or visible
    $("p.warning").css("visibility", (matches) ? "visible" : "hidden");
});

Solution 3:

You can filter based on HTML elements' attribute contents with jQuery to either contain, start, or end with a string that you want. To match elements with an attribute that contain a string, you'd use [attr*="value"] in your jQuery selector, but I think that you want something where the end matches your string. Here's how that would work:

var elements = $(".email[value$='@nyu.edu']");
if(elements.length > 0) {
    // Do something with the elements, such as removing an .error class
} else {
    // Email doesn't end with @nyu.edu
}

Read more about the jQuery ends-with attribute selector or browse through other attribute selectors like this.

Solution 4:

jsBin demo

var $warning = $("p.warning"); // P.S. make sure not to target a wrong .warning!
$('.email').on("input", function(){
    $warning.toggle( /@nyu\.edu/ig.test(this.value) );
});

as I've mentioned .warning being a class can represent any first .warning occurrence. use rather some other selector like .next() or .closest(selector).find(".warning")

your boss fill fire you if your client loses $$$ cause you forgot to watch for copy-paste cases. ;) Kidding, use "input" event.

P.S use .warning{display:none;} instead of visibility

Post a Comment for "Check If Input Fields Contains Certain Text"