简体   繁体   中英

Allow and Prevent postback in javascript in asp.net

I was trying to validate dates using java script on button click event.If validation returns false post-back should be prevented and if returns true post-back should be allowed.

The problem is that post-back is occuring even if the validation returns false.....

I'm new to javascript.Kindly give me any solution.....

Here's my code

<script type="text/javascript">
    function ValidateDate() {

        var GridView = document.getElementById('GridView1');           
        var i = 1;
        var rows = GridView.rows.length;           
        for (var j = 0; j < rows - 2; j++) {
            i = i + 1;              
            var FromDate = new Date(document.getElementById('GridView1_ctl0' + i + '_txtFrom').value);
            var ToDate = new Date(document.getElementById('GridView1_ctl0' + i + '_txtTo').value);
            if (ToDate < FromDate) {
                document.getElementById('GridView1_ctl0' + i + '_txtFrom').focus();
                alert('ToDate is less than from date');
                return false;
            }
        }
        return true;      
    }
</script>

I've called javascript on pageload event

this.btnSave.Attributes.Add("onClick", "ValidateDate();");

You forgot to specify return

You should try with:

this.btnSave.Attributes.Add("onClick", "return ValidateDate();");

You are returning the value back from the ValidateDate() so for such a condition you need to specify this at the time of function call, and when it returns false then it stops the execution further..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM