Panky031
Panky031

Reputation: 443

How to call a JavaScript function from a button onclick in JSP page

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        <%@page import="java.util.Map" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Login page</title>
    </head>
    <body>
     <link rel="stylesheet" type="text/css" href="css/login.css"/>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />

    <form action="LoginS" method="post">  
       <button type="submit"  onclick="javascript:MyFunction();">Login</button>
      <div class="container" style="background-color:#f1f1f1">
        <button type="button" class="cancelbtn">Cancel</button>
        <span class="psw">Forgot <a href="#">password?</a></span>
      </div>

      <script type="text/javascript">
    MyFunction(){
                 alert("java Script");
    }
    </script>
     </form>
    </body>
    </html>

Above is my code that I'm trying to call JavaScript function from the submit button onclick() event but its showing nothing. Am I doing any wrong in code.

When I click on the button nothing happens. I want the string value in the text box to be printed on the console.

Upvotes: 3

Views: 15525

Answers (1)

Mahsa Lotfi
Mahsa Lotfi

Reputation: 77

I've made some changes to make your code working and print "java script" in the console since there isn't any text box in your code :) I've also added a textbox to your code and printed its value as a sample for you.

I changed the type of login button to "button" and defined MyFunction as a function.

I also made a fiddle for it to test.

<form action="LoginS" method="post">  
    <button type="button"  onclick="javascript:MyFunction()">Login</button>
    <input id="text-box"/>
    <div class="container" style="background-color:#f1f1f1">
        <button type="button" class="cancelbtn">Cancel</button>
        <span class="psw">Forgot <a href="#">password?</a></span>
    </div>

    <script type="text/javascript">
        MyFunction = function(){
            console.log("java Script");
            console.log(document.getElementById("text-box").value);
        }
    </script>
</form>

Upvotes: 3

Related Questions