1

I want to check the value of a textbox that whether it contains a particular set of strings or not. How do I do this? (preferably using jquery)

I have a textbox where a user enters something. I want to check whether the string he enters contains BOTH "@" and "port". Please help..

I tried using contains but it is giving false positives.

Here is the code I used.

if($("#id:contains('@'):contains('port')")) {
    $("#1st").hide();
    $("#2nd").show();
} else {
    alert("Wrong value entered.");
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Kaustubh
  • 1,475
  • 2
  • 12
  • 12

3 Answers3

2

Use $('#id').val() to get the value. Then you can use regular JavaScript functions to check if it contains certain values.

var value = $('#id').val();
if(~value.indexOf('@') && ~value.indexOf('port')) {
    $("#1st").hide();
    $("#2nd").show();
} else {
    alert("Wrong value entered.");
}

In case you wonder what the ~ does: it's a smart way to check for != -1 as ~-1 == 0.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

Here is basic solution with other example which is very simple and won't need any other file to be imported.


function check()

{

    var val = frm1.uname.value;
    //alert(val);
    if (val.indexOf("@") > 0)
    {
        alert ("email");
        document.getElementById('isEmail1').value = true;
    }else {
        alert("usernam");
          document.getElementById('isEmail1').value = false;
    }
}
MankitaP
  • 57
  • 1
  • 1
  • 7
-1

Try a combination of javascript and jQuery

var txtVal = $("#id").attr('value');
if(txtVal.indexOf("@")!= -1 && txtVal.indexOf("port")!= -1)
   alert('yes');
else
   alert('no');
afrin216
  • 2,295
  • 1
  • 14
  • 17
  • `.attr('value')` is **bad**. Use `.val()` instead! – ThiefMaster Jul 30 '12 at 07:27
  • CrossBrowser compatibility issues are there for .val(). Sometimes it doesn't work for all the DOM elements in all browsers – afrin216 Jul 30 '12 at 07:28
  • I **highly** doubt that. jQuery functions are cross-browser-compatible. Probably it's your code that's broken if it doesn't work for you. The only reason `.attr('value')` currently works is that jQuery has an internal fallback to the *property*. However, this will be removed in a future version and then it **will** break: http://jsfiddle.net/YRNfC/ – ThiefMaster Jul 30 '12 at 07:31
  • @ThiefMaster I experimented a lot now and found .val() to be the more stable and consistent method. Thanks for the tip up. – afrin216 Jul 30 '12 at 08:57