user2211833
user2211833

Reputation: 13

I want to detect if a user types a certain string into a textbox

I have a textbox that looks like this

<%= Html.TextBoxFor(model => model.ContactAddress, new { autocomplete = "off", maxlength = "75" })%>

in my javascript i have this

   $('.save_button_cont').click(function (e) {


        var addr1 = $('#ContactAddress').val();

        if(addr1.indexOf("box") > -1) {
            alert("HEY NO P.O. BOXES ALLOWED ");
        }

            document.forms[0].submit();
        });

i was hoping that this would pop up the alert before posting if the user had 'box' in the textbox. it doesnt work though.

I want to show an alert if the user enters the string 'box' in their address (the textbox).

EDIT: on the submit i am going to use a confirm box to verify that the user wants to continue. thanks for the help

Upvotes: 1

Views: 144

Answers (5)

Venkata K. C. Tata
Venkata K. C. Tata

Reputation: 5547

Using

$("#textboxid").blur(function(){
if( $("#textboxid").val() == "box"){
alert("box typed!");
}
});

this will make your life easy!

Upvotes: 1

Corey
Corey

Reputation: 5818

You could use regex to test the string for the occurrence of "box". This will allow you to do a case-insensitive search:

$('input[type="submit"]').click(function(e) {
    e.preventDefault();
    var input = $('#test').val();
    if (/box/i.test(input)) {
        alert("bad");
    } else {
        alert("good");
        $("form").submit();
    }
});

You should also put the "submit" function in your "else" statement so the form only submits on validation success.

NOTE: this could cause unwanted issues if the user happens to live on "box street".

Upvotes: 1

eklhad
eklhad

Reputation: 270

Instead of:

if(~addr1.indexOf("box")) {...} else {...}

Try

if(addr1 === "box") {...} else {...}

Upvotes: 1

palaѕн
palaѕн

Reputation: 73896

You can do this:

$('.save_button_cont').click(function (e) {
    var addr1 = $('#ContactAddress').val();
    if (addr1.indexOf("box") > -1) alert("blah");
    else alert('Bleh');
    $('#formID').submit();
});

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try this -

$('.save_button_cont').click(function (e) {
      var addr1 = $('#ContactAddress').val();
            if(addr1.indexOf("box") > -1) {
                alert("blah");
            }else {
                alert('Bleh');
            }
            alert("TEST");

            $('form').eq(0).submit();
        });

Upvotes: 1

Related Questions