javascript Prevent from Submit

Asked

Viewed 135 times

1

I have a text box and a button . I just want to check the value of the text box with javascript and prevent it from displaying, if it is null.

Here is aspx :

<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<asp:Button CssClass="addButtonBlack" ID="ButtonAddDriver" OnClientClick="return IsNull();" OnClick="ButtonAddDriver_Click" runat="server" Text="Ekle" />

And my javascript code:

function IsNull() {
        var success = true;

        var name = document.getElementById('TextBoxName');
        if (name.value == "") {
            name.style.borderColor = '#e52213';
            name.style.border = 'solid';
            success = false;
        }
        if (success)
            return true;
        else
            return false;
        }

The text box is null. How can I prevent this?

2 answers

3

You can use the javascript method Event.preventDefault() to prevent the default event from running

Follow a practical example:

$("a").click(function(event){
    event.preventDefault();
});

A little deeper, you can check the returning text and perform a validation using regular expression, returning true or false to the condition set by you.

Would look like this:

    $("#buscarID").click(function(e){
        var texto = $("#buscar").val();
        if(validaString(texto)){
            // chama algo
        }else{
            e.preventDefault();
        }
    });

 //Aqui ele só irá retornar true, caso o value for um texto de a-z ou numeros.
 function validaString(value){
     var filter = /[a-zA-Z0-9]+/;
     if(filter.test(value)){return true;}
 }
  • Preserving good practices, it would be interesting to put a false Return in the Tring() function, because if not hitting with the expression will not return anything, it will result in a Undefined. But your solution, I believe, solves his problem.

1


You must have something like: OnClientClick = "IsNull"

function isNull(e) {
  if (it is null) e.preventDefault();
  else ... 
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.