1

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.

Community
  • 1
  • 1
hlyates
  • 1,279
  • 3
  • 22
  • 44
  • 1
    Try using an onload function `$(function(){})` or putting your scripts before `

    `

    – A1rPun Oct 06 '14 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 Oct 06 '14 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 Oct 06 '14 at 20:11
  • @OJay I added that code snippet as requested. – hlyates Oct 06 '14 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. – hlyates Oct 06 '14 at 21:13

4 Answers4

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();
    });
});
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
3

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.net/4pwakehm/

C Bauer
  • 5,003
  • 4
  • 33
  • 62
  • I don't understand the comment about calculate on button click. Usually, it's preferable to listen to the `submit` event because you can also submit the form using the enter key. – Ruan Mendes Oct 06 '14 at 20:16
  • The reason I say that is, when you're doing something with javascript or jquery you're generally concerning yourself with client-side scripts. However if you run javascript at the same time as a postback, your javascript won't do anything because when the page refreshes, the values that the javascript edited will all be reset to what they were before you pressed the button. – C Bauer Oct 06 '14 at 20:18
  • @CBauer Agreed. That is what I am trying to do. I think I bit off more than I can chew with this tutorial. I suspect something is wrong in my application because I am not getting the alert when I try this in my application. – hlyates Oct 06 '14 at 20:52
3

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>
OJay
  • 4,763
  • 3
  • 26
  • 47
  • I face palmed hardcore reading this well written response. Do you have any suggestions for good jQuery and javascript books? – hlyates Oct 06 '14 at 20:56
  • I modified my code with your suggestions and fixed the errors. However, I might have bigger issues going on as VS13 is not able to debug the javascript? – hlyates Oct 06 '14 at 21:02
  • 2
    IMO - Learn JavaScript first. jQuery is just a JavaScript library. Most people I know never started with a book and self-taught (including myself) although I read several JavaScript books but that was in later years. I thought JavaScript the Definitive Guide by O'Reilly to be the best resource (I have gone through it probably half a dozen times), although it is a massive book and will take months if not years to master. Douglas Crockfords JavaScript the good parts, and John Resign Secrets of the JavaScript Ninja also to be good, although the second two are intermediate - advance. – OJay Oct 06 '14 at 21:04
  • To debug in VS2013, you need to be running IE and your JavaScript needs to be in a seperate file – OJay Oct 06 '14 at 21:05
  • You can of course use the in browser debugger in Chrome, FireFox and IE – OJay Oct 06 '14 at 21:07
  • OJay, I am using IE11 and VS13, but I appreciate knowing the limitations. Any of books you would like to recommend? I am super eager to learn and become an advanced developer in this area. Especially .NET MVC material. – hlyates Oct 06 '14 at 21:11
  • 1
    @hlyates I don't think there is a simple answer to your question. Learn JavaScript, jQuery .NET, ASP.NET MVC all at once is a massive path ahead of you. I have done courses on .NET, I learnt Javascript mainly from doing it myself and trial and error. On-line resources are vast and numerous but sometimes can be confusing. IMO you can only learn by doing, practice makes perfect. Resources online can easily be found, just google it. but for some quick links [JavaScript](http://www.w3schools.com/js/) - [MVC](http://www.asp.net/mvc/tutorials) - w3schools has it critics, but I have found it useful – OJay Oct 06 '14 at 21:24
  • A long journey starts with a single step. I've taken that step. Thanks for your help. – hlyates Oct 06 '14 at 21:54
1

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.

Greg
  • 11,302
  • 2
  • 48
  • 79
  • This is a valid comment about console. Unfortunately, this issue appeared for me: http://stackoverflow.com/questions/16936209/the-breakpoint-will-not-currently-be-hit-no-symbols-have-been-loaded I am using VS13 and IE11. – hlyates Oct 06 '14 at 20:51