0

I have 3 text boxs: Height, Weight, BMI and a Button called "Calculate" the JS function has to calculate the BMI of the person that clicks the button "Calculate", but it doesn't seem to work, I click the button and it does nothing, why is that? Do I have to create other class to put the JS code?

This is the edited view and the JS function :

   @model IEnumerable<FitnessWebApplication.Models.Measurement>

@{
    ViewBag.Title = "Index";
}



    <script src="jquery.js"></script>

    <script>

        @section scripts{
            $(document).ready(function () {
                $('#calculate').click(function () {
                    var weight = Number($('#Weight').val());
                    var height = Number($('#Height').val());
                    var bmi = height / (weight * weight);
                    $('#BMIBox').val(bmi);
                });
            });//jq
        }
    </script>

<h2>Your Measurements</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">


    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Weight)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Height)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Neck)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Waist)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Taken)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Weight) kg
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Height) cm
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Neck) cm
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Waist) cm
            </td>
            <th>
                @Html.DisplayFor(modelItem => item.Taken)
            </th>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.ID })
            </td>
        </tr>
    }

</table>

<hr />

<h1>Calculate</h1>
<hr />
<h2>BMI</h2>

<form>



    <table>

        <tr>
            <td align="right"><b>Weight:</b></td>
            <td align="left"><div class="col-xs-5"><input type="text" name="Weight" class="form-control" id="Weight" /></div><b>kg</b></td>
        </tr>
        <tr>
            <td align="right"><b>Height:</b></td>
            <td align="left"><div class="col-xs-5"><input type="text" name="Height" class="form-control" id="Height" /></div><b>cm</b></td>
        </tr>
        <tr>
            <td align="right"><b>BMI:</b></td>
            <td align="left"><div class="col-xs-4"><input type="text" name="BMI" class="form-control" id="BMIBox" /></div></td>
        </tr>
    </table>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="button" value="Calculate" class="btn btn-default" id="calculate" />

        </div>

    </div>



</form>

<hr />
<h2>BF% (aproximated)</h2>
<p>(All the measurements must be taken at the narrowest point)</p>

<form>
    <table>
        <tr>
            <td><b>Male</b></td>
            <td><input type="radio" name="Male" /></td>
            <td><b>Female</b></td>
            <td><input type="radio" name="Female" /></td>
        </tr>
        <tr>
            <td align="right"><b>Height:</b></td>
            <td align="left"><div class="col-xs-5"><input type="text" name="Height" class="form-control" /></div><b>cm</b></td>
        </tr>
        <tr>
            <td align="right"><b>Waist:</b></td>
            <td align="left"><div class="col-xs-5"><input type="text" name="Waist" class="form-control" /></div><b>cm</b></td>
        </tr>
        <tr>
            <td align="right"><b>Hip:</b></td>
            <td align="left"><div class="col-xs-5"><input type="text" name="Hip" class="form-control" /></div><b>cm</b></td>
        </tr>
        <tr>
            <td align="right"><b>Neck:</b></td>
            <td align="left"><div class="col-xs-5"><input type="text" name="Neck" class="form-control" /></div><b>cm</b></td>
        </tr>
        <tr>
            <td align="right"><b>BF%:</b></td>
            <td align="left"><div class="col-xs-4"><input type="text" name="BF%" class="form-control" /></div><b>%</b></td>
        </tr>
    </table>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="button" value="Calculate" class="btn btn-default" onclick="location.href='<%: @Url.Action("CalculateBF", "Measurements") %>'">
        </div>
    </div>


</form>
4
  • Open your browser console and see whether you have any script errors. Commented Aug 19, 2018 at 17:56
  • Let's think about event handlers, like $("#element").click(). This says "Find anything with an ID of element, and attach a click event to it." Pretty simple, right? But what if you tried to do that before element was even on the page? That's what your code is doing. You're not waiting for #calculate to load before you try and attach things to it. The selector $("#calculate") won't find anything on the page. Try wrapping it in a $(document).ready(function() { ... }); instead. Commented Aug 19, 2018 at 18:31
  • Already tried that, but is not working. Commented Aug 19, 2018 at 18:45
  • The @section scripts{} needs to @RenderSection("scripts") to adding it to a special point of your view and you must use it only when your view uses a Layout. In a simple (without layout) .cshtml file, you should use simple <script> tag. Commented Aug 20, 2018 at 3:08

2 Answers 2

1

Try this:

<script src="jquery.js"></script>
<script>
    $(function(){
         $('body').on("click", "#calculate" , function () {
              var weight = Number($('#Weight').val());
              var height = Number($('#Height').val());
              var bmi = height / (weight * weight);
              $('#BMIBox').val(bmi);
        });
     });
</script>

Important things:

  • first $(function(){}) is equals to document.ready.

  • address of js file. Your src must based on the view file. If the jquery.js is exactly beside final html, your src is correct. If the jquery file exists in root, you can try this: src="/jquery.js"

  • If you want to check that your scripts is executed, add this line before binding click event: alert("Reached here!");

  • priority of running scripts. jQuery must load before other scripts.

  • press F12. Now in console tab, type this: $("div")

If you get correct answer, jquery is loaded successfully.

  • use .on() when your element may be added to page later (or exists now). Thus, in this sample it is not necessary.

Tip:

.cshtml files, compiles to simple html outputs. Only if you want to use layouts, sections are useful.

Scripts are a common part of html file, thus you can add them without any extra parts.

My above code will be correct, when you wrap all html tags in <body></body>

Sign up to request clarification or add additional context in comments.

1 Comment

At last I was able to make it work, the problem was in the <script src="jquery.js"></script>
1
  1. You are using asp.net-mvc
  2. You have also using shared layout for, Folder : views/Shared/_Layout.cshtml

Solution is in following steps

  1. Make sure you have included jQuery on shared layout
  2. You must apply @RenderSection("scripts", required: false) after including jquery in shared layout file
  3. After that open second file where you want to apply click event
  4. apply your jQuery only between below code:

@section scripts{
    <script>
    	$(document).ready(function(){    
                //Your code will be here
            });//jq
    </script>
}

3 Comments

By " your code will be here" you mean all this code?: $('#calculate').click(function () { var weight = Number($('#Weight').val()); var height = Number($('#Height').val()); var bmi = height / (weight * weight); $('#BMIBox').val(bmi); });
Yes, also use your browser console to check any other.
Do the @section scripts{ $(document).ready(function(){ //Your code will be here });//jq } has to be between <script> </script> tags, I have edited my code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.