admin管理员组

文章数量:1323714

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.

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.

Share Improve this question edited May 23, 2017 at 12:08 CommunityBot 11 silver badge asked Oct 6, 2014 at 20:03 GeekyOmegaGeekyOmega 1,3393 gold badges24 silver badges44 bronze badges 5
  • 1 Try using an onload function $(function(){}) or putting your scripts before </body> – A1rPun Commented Oct 6, 2014 at 20:07
  • the sample code you here will not work, because it is not in the document ready (or not at the end of the page, simply '.my-calc' (should be '#my-calc' anyway) does not exist when the script runs, so no submit handler is added). You say that you rewrote documents.on.ready() and it didn't work? Are you able to supply that code? – OJay Commented Oct 6, 2014 at 20:08
  • You also really don't want to put that submit button it its own sub-form. Per HTML5 standards, you don't put forms inside of forms...it can make their submit behaviors all wonky. Instead, you may want to set the ID of the Html.BeginForm(). Like so: using (Html.BeginForm(null, null, FormMethod.Post, new { id = "my-calc" })) – guildsbounty Commented Oct 6, 2014 at 20:11
  • @OJay I added that code snippet as requested. – GeekyOmega Commented Oct 6, 2014 at 20:19
  • I gave everyone upvotes. I appreciate the gentle help you gave me, a beginner. I wish I could give everyone credit for answering this. Ojay answered the question as his was the first solution I got to work. Special thanks for pointing out debugging in the browser. If you have any books you like to suggest. Please let me know. – GeekyOmega Commented Oct 6, 2014 at 21:13
Add a ment  | 

4 Answers 4

Reset to default 4

You're running your code before your form is rendered. Therefore, $('.my-calc') is returning an empty object, and doing nothing. Also, the selector for an item by ID is $('#my-calc'), your selector was looking for an element with class my-calc

// Passing a function into `$()` makes it run after the DOM is ready.
$(function() {
    $('#my-calc').on('submit', function (){
        alert("This button is working?");
        calculate();
    });
});

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>

For ids in jquery, you have to use #my-calc

But frankly, I think you're looking to call calculate on the button click otherwise you're going to have to submit your form every time you press the button, which kinda defeats the purpose of the javascript.

$("input").on("click", calculate);

http://jsfiddle/4pwakehm/

Your code isn't working because you don't have # in your Javascript.

  • # should be in front of the name, to represent an Id.
  • The . should be in front of the name, to represent an class.

You could is essentially do:

$(document).ready(function () {
     $("#my-calc").on("click", function () {
          alert("Triggered alert for click.");
     });
});

Keep in mind that with $(document).ready utilizes jQuery.

That is an example, you should also use your console in the browser to help debug Javascript. Which will help troubleshoot such issues.

本文标签: