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.
`
– A1rPun Oct 06 '14 at 20:07