简体   繁体   中英

How to Call JavaScript function on checkbox click event in Asp.Net MVC

How to Call JavaScript function on checkbox click event in Asp.Net MVC This code is not working

@{
   ViewBag.Title = "Employee";
   Layout = "~/Views/Shared/_MasterLayout.cshtml";
 }
<head>
    <script type="text/javascript">
        function Myfunction()
        {
            alert("Hello");
        }
    </script>
</head>
<body>
      <input type="checkbox" id="chk1" onclick="Myfunction()" />
</body>

You should have your js code inside Body tag (at bottom). As Js can't able to get any Dom element as it loaded first Before Whole DOM itself. Ex:-

<!DOCTYPE html>
<html>
<body>

<h1>Test</h1>
 <input type="checkbox" id="chk1" onclick="Myfunction()" />
<script>
        function Myfunction()
        {
            alert("Hello");
        }
    </script>

</body>
</html>

Also you can use Third party Lib to make productivity Fast USING ( jQuery )

<input type="checkbox" id="checkbox1" />

$("#checkbox1").click( function(){
   // YOUR FUNCTION CODE
});
Just Refer this link,you will get complete idea about it
Hope it helps..Cheers

https://jsfiddle.net/a6cedoj0/

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