简体   繁体   中英

how to jquery event bind to function

<input id='btnExcelRead' name='btnExcelRead' type='submit' runat='server'/>   <- actually asp:button
<input id='excelUpload' name='excelUpload' type='file' />   
<input id='txtStartDate' type='text' />
<input id='txtEndDate' type='text' />

..

$(function(){

          $("#btnExcelRead").click(CheckValidation);

        });

        var CheckValidation = function() {
            if ($("#excelUpload").val() === "") {
                alert("Select file");
                return false;
            }
            if ($("$txtStartDate").val() === "") {
                alert("Check the start date!");
                return false;
            }
            if ($("$txtEndDate").val() === "") {
                alert("Check the end date!");
                return false;
            }
        }

here i made simple jquery code.

I want to bind function when btnExcelRead button click.

is this originally wrong way?

What you have is valid, aside from the selectors, I would reformat is a bit, like this:

$(function(){
      $("#btnExcelRead").click(CheckValidation);
});

function CheckValidation () {
    if ($("#excelUpload").val() === "") {
        alert("Select file");
        return false;
    }
    if ($("#txtStartDate").val() === "") {
        alert("Check the start date!");
        return false;
    }
    if ($("#txtEndDate").val() === "") {
        alert("Check the end date!");
        return false;
    }
}

You can see a demo of it working here

You have $txtStartDate and $txtEndDate for your selectors, I think you meant #txtStartDate and #txtEndDate here (I assume you're finding them by ID). Also if you want a named function, just make one :) If you store a variable pointing to a anonymous function, make sure to put a ; after it, since that's a statement.

$("#btnExcelRead").click(function(){CheckValidation()});

You have to declare the callback before calling it like follows:

    var CheckValidation = function() {
        if ($("#excelUpload").val() === "") {
            alert("Select file");
            return false;
        }
        if ($("$txtStartDate").val() === "") {
            alert("Check the start date!");
            return false;
        }
        if ($("$txtEndDate").val() === "") {
            alert("Check the end date!");
            return false;
        }
    }

    $(function(){

      $("#btnExcelRead").click(CheckValidation);

    });

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