Why is my javascript function not being invoked for simple MVC tutorial? Why can't I debug either?

hlyates

Problem

I have been following this simple tutorial found here. However, I want to modify it so that the calculator is only invoked when the client clicks submit. However, when I click the submit button, no action is observed. I am not even seeing the alert.

EDIT:

I have modified the code per Ojay's suggestions. However, I am getting this error when I try to debug. I am getting this exact issue except I have VS13 Update 3. Multiple things going on here?

Code

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Sample Calculator</title>
    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">


        $(document).ready(function () {
            $('#my-calc').on('submit', function () {
                alert("This button is working?");
                calculate();
            });



           function calculate()
           {

               alert('hi');
               //Add 
               try {

                   $('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));

               } catch (e) {

               }

               //Subtract
               try {

                   $('#sub').val((parseInt($('#num1').val())) - parseInt($('#num2').val()));

               } catch (e) {

               }

               //Multiply
               try {

                   $('#mul').val((parseInt($('#num1').val())) * parseInt($('#num2').val()));

               } catch (e) {

               }

               //Divide
               try {

                   $('#div').val((parseInt($('#num1').val())) / parseInt($('#num2').val()));

               } catch (e) {

               }
           }

        });



    </script>

</head>
<body>
    <div><h4>Sample Calculator</h4></div>
    @using (Html.BeginForm())
    {
        <p> @Html.Label("Input 1") : @Html.TextBox("num1","0")</p>
        <p> @Html.Label("Input 2") : @Html.TextBox("num2", "0")</p>
        <p> @Html.Label("Sum ") : @Html.TextBox("sum")</p>
        <p> @Html.Label("Sub ") : @Html.TextBox("sub")</p>
        <p> @Html.Label("Mult ") : @Html.TextBox("mul")</p>
        <p> @Html.Label("Div ") : @Html.TextBox("div")</p>
        <button id="my-calc" type="button">Calculate</button>


    }   
</body>
</html>

Attempts

  • Put in alert. Not observed.
  • Rewrote it from documents.on.ready(). See below.
  • RTFM as seen here
  • Searched stackoverflow. Didn't find anything that worked.

Edit: I had something originally like the tutorial I was looking at. I had:

    $(document).ready(function(){

  $('#my-calc').on('submit', function (){ //stuff}


    }

I don't understand why my function is not being invoked? My form id is correct. All I want to do is invoke this calculator method so my label's sum, sub, mult, and div display the results.

Please pardon the simplistic nature of this question, but I feel it would be useful for others doing .NET MVC tutorials who might also be having this problem. As a result of this question, I decided to obtain a book on jQuery. Thanks for your assistance.

OJay

It looks as though there are multiple issues here.

Firstly your selector must be '#my-calc' to correctly select the submit form. Your jQuery code must be wrapped in a document ready handler (as per your added code), or the code needs to appear after the form. Also when you add a submit event handler then you need to return false to stop the form submitting. And lastly (and perhaps the most important), you cannot nest forms. The @using (Html.BeginForm()) creates a form, and then you are creating another one inside it <form id="my-calc">, this is not valid. What the browser will do is just ignore the inner one, so in other words, there will never be a submit event of the my-calc form, becuase the parent form is what is submitted.

Also because you are just doing a calculation on the page with JavaScript, there is no real need for a form anyway, perhaps just a <button type="button" id="my-calc">Calculate</button> would be better with a click event.

Now your calculate function also has errors

every calculation line is missing a $ in the attempt to get the num1 value

so

$('#sum').val((parseInt(('#num1').val())) + parseInt($('#num2').val()));

should be

$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));

and there is an additional issue with the multiplication one, the input is not #mult its #mul as per your @Html.TextBox("mul").

So all of that together, something like the following should resolve your issues

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Sample Calculator</title>
    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            $('#my-calc').on('click', function () {
                calculate();
            });

            function calculate() {
                //Add
                try {

                    $('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));

                } catch (e) {

                }

                //Subtract
                try {

                    $('#sub').val((parseInt($('#num1').val())) - parseInt($('#num2').val()));

                } catch (e) {

                }

                //Multiply
                try {

                    $('#mul').val((parseInt($('#num1').val())) * parseInt($('#num2').val()));

                } catch (e) {

                }

                //Divide
                try {

                    $('#div').val((parseInt($('#num1').val())) / parseInt($('#num2').val()));

                } catch (e) {

                }
            }
        });
    </script>

</head>
<body>
    <div><h4>Sample Calculator</h4></div>
    <p> @Html.Label("Input 1") : @Html.TextBox("num1", "0")</p>
    <p> @Html.Label("Input 2") : @Html.TextBox("num2", "0")</p>
    <p> @Html.Label("Sum ") : @Html.TextBox("sum")</p>
    <p> @Html.Label("Sub ") : @Html.TextBox("sub")</p>
    <p> @Html.Label("Mult ") : @Html.TextBox("mul")</p>
    <p> @Html.Label("Div ") : @Html.TextBox("div")</p>
    <button id="my-calc" type="button">Calculate</button>  
</body>
</html>

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

I don't know why my tracking beacon isn't being sent as I debug my Google Analytics

分類Dev

Why can't I access my JavaScript array by index outside of the d3 then function?

分類Dev

Why is my function not being called?

分類Dev

Why my simple T-Sql Function can not run in Query WIndow?

分類Dev

Why can't I step into a Call instruction during Debug / Disassembly?

分類Dev

Why can't I parse the html result returned by my MVC partial view?

分類Dev

Why won't my HTML button run my JavaScript function?

分類Dev

Why can invoked functions be prefixed with a name + colon in JavaScript

分類Dev

Why can invoked functions be prefixed with a name + colon in JavaScript

分類Dev

Why can't I access my private variable inside a function in PHP?

分類Dev

Weird examples in javascript, why I can't reassign a global variable's value through a function's parameter?

分類Dev

Why can't I assign to a variable a JSON value that I can see in Debug mode?

分類Dev

Why doesn't my javascript function throw up an error?

分類Dev

WhY I can not send debug or appstore build?

分類Dev

My prime number function is broken but I don't know why

分類Dev

Why can't I select cells in my WPF datagrid?

分類Dev

Why can't I use my column alias in WHERE clause?

分類Dev

Why can't I extend my desktop 12.04 in KDE?

分類Dev

Why can't I crash my system with a fork bomb?

分類Dev

Why can't I see remote video in my WebRTC app?

分類Dev

Why can't I open my txt file in Ubuntu?

分類Dev

Why can't I download my package through packagist?

分類Dev

Why can't I access my objects member variable?

分類Dev

Why can't I hit the breakpoint when I start debug the Xamarin Android Application?

分類Dev

Why can't I call class function inside addEventListener

分類Dev

why can't I pass companion object to a function

分類Dev

Why can't I call a generic function with a union type parameter?

分類Dev

Why can't I see CloudWatch Logs for Lambda function?

分類Dev

Why can't I use "." as a delimiter in split() function?

Related 関連記事

  1. 1

    I don't know why my tracking beacon isn't being sent as I debug my Google Analytics

  2. 2

    Why can't I access my JavaScript array by index outside of the d3 then function?

  3. 3

    Why is my function not being called?

  4. 4

    Why my simple T-Sql Function can not run in Query WIndow?

  5. 5

    Why can't I step into a Call instruction during Debug / Disassembly?

  6. 6

    Why can't I parse the html result returned by my MVC partial view?

  7. 7

    Why won't my HTML button run my JavaScript function?

  8. 8

    Why can invoked functions be prefixed with a name + colon in JavaScript

  9. 9

    Why can invoked functions be prefixed with a name + colon in JavaScript

  10. 10

    Why can't I access my private variable inside a function in PHP?

  11. 11

    Weird examples in javascript, why I can't reassign a global variable's value through a function's parameter?

  12. 12

    Why can't I assign to a variable a JSON value that I can see in Debug mode?

  13. 13

    Why doesn't my javascript function throw up an error?

  14. 14

    WhY I can not send debug or appstore build?

  15. 15

    My prime number function is broken but I don't know why

  16. 16

    Why can't I select cells in my WPF datagrid?

  17. 17

    Why can't I use my column alias in WHERE clause?

  18. 18

    Why can't I extend my desktop 12.04 in KDE?

  19. 19

    Why can't I crash my system with a fork bomb?

  20. 20

    Why can't I see remote video in my WebRTC app?

  21. 21

    Why can't I open my txt file in Ubuntu?

  22. 22

    Why can't I download my package through packagist?

  23. 23

    Why can't I access my objects member variable?

  24. 24

    Why can't I hit the breakpoint when I start debug the Xamarin Android Application?

  25. 25

    Why can't I call class function inside addEventListener

  26. 26

    why can't I pass companion object to a function

  27. 27

    Why can't I call a generic function with a union type parameter?

  28. 28

    Why can't I see CloudWatch Logs for Lambda function?

  29. 29

    Why can't I use "." as a delimiter in split() function?

ホットタグ

アーカイブ