The submit() Method


The jQuery submit() method attach an event handler function to the <form> elements that is executed when the user is attempting to submit a form. The following example will display a message depending on the value entered when you try to submit the form.

Example

<script>
$(document).ready(function(){
    $("form").submit(function(event){
        var regex = /^[a-zA-Z]+$/;
        var currentValue = $("#firstName").val();
        if(regex.test(currentValue) == false){
            $("#result").html('<p class="error">Not valid!</p>').show().fadeOut(1000);
            // Preventing form submission
            event.preventDefault();
        }
    });
});
</script>

Tip: A form can be submitted either by clicking a submit button, or by pressing Enter when certain form elements have focus.

Document/Window Events

Events are also triggered in a situation when the page DOM (Document Object Model) is ready or when the user resize or scrolls the browser window, etc. Here’re some commonly used jQuery methods to handle such kind of events.

The ready() Method

The jQuery ready() method specify a function to execute when the DOM is fully loaded.

The following example will replace the paragraphs text as soon as the DOM hierarchy has been fully constructed and ready to be manipulated.

Example

<script>
$(document).ready(function(){
    $("p").text("The DOM is now loaded and can be manipulated.");
});
</script>

The resize() Method

The jQuery resize() method attach an event handler function to the window element that is executed when the size of the browser window changes.

The following example will display the current width and height of the browser window when you try to resize it by dragging its corners.

Example

<script>
$(document).ready(function(){
    $(window).resize(function() {
        $(window).bind("resize", function(){ 
            $("p").text("Window width: " + $(window).width() + ", " + "Window height: " + $(window).height());
        });
    });
});
</script>

The scroll() Method

The jQuery scroll() method attach an event handler function to the window or scrollable iframes and elements that is executed whenever the element’s scroll position changes.

The following example will display a message when you scroll the browser window.

Example

<script>
$(document).ready(function(){
    $(window).scroll(function() {
        $("p").show().fadeOut("slow");
    });
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *