开发者

How do i validate a textfield on button click with jQuery?

How can i use jQuery to validate if a textbox is not empty and consists of digits, when i click on a button?

This is the code i have so far:

HTML:

<input type="button" name="Tilføj" value="Tilføj" id="add" />
<input type="text" id="element" name="element" />
&开发者_运维百科lt;div id="result"></div>

Javascript:

$(document).ready(function () {

    $("#add").click(function () {

        $("#element").validate({
            rules: {
                element: {
                    required: true,
                    number: true
                }
            },
            errorHandler: function () {
                $("#result").append("error");
            },
            submitHandler: function () {
                $("#result").append("good");
            }

        });

    });
});

Do i have to use jQuery validation inside a form for it to work?


You can do this without a jQuery plugin. All you need is a simple Regular expression to validate your input format. You can customize it for different type of inputs

<script language="javascript" type="text/javascript">  

function validate_input( inputText)
    {
        if( inputText.length > 0 )
        {
            // Search for non-digit pattern (\D) globally
            var patt=/\D/g ;

            if( patt.test( inputText ) )
                return false;
            else
                return true;
        }
        else
            return false;
    }

$(document).ready(function () 
{      
    $("#add").click(function () 
    {

        if( validate_input( $("#element").val() ) )
        {
            $("#result").html("<label> good </label>");
        }
        else
        {
            $("#result").html("<label> error </label>");
        }
    });

});     


You can do it without jQuery using <input type="number" id="element" name="element" required /> and the full code being:


<form>
  <input type="number" id="element" name="element" required />
  <input type="submit" value="Go">
</form>


$(document).ready(function() {
    $("form").validate({
        rules: {
            element: {
                required: true,
                number: true
            }
        },
        errorHandler: function () {
            $("#result").append("error");
        },
        submitHandler: function () {
            $("#result").append("good");
        }

    });

    $('#add').click(function() {
        $('form').validate();
    });
});


Take a look at this

http://docs.jquery.com/Plugins/validation

//AJAX way to submit the form

$("form").submit(function(e) {
    e.preventDefault();

    $.post( {
       url: $(this).attr("action"), 
       data: $(this).serialize(),
       success: function(){ 

           //Write code here to handle on success 

        }
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜