How to change @html object attributes based on value

时间:2019-03-19 14:54:59

标签: javascript c# asp.net-mvc-5

I have an Edit View in MVC5 / C#. Within that view, there is an @html.TextBox which contains an integer. If that integer is less than zero, I would like to change the Textbox to bold and red. And change some other html object (attributes) - like a drop down box to be locked.

I have looked at some stuff with JScript but it is very new to me. And I can't quite get there. Not even sure if JScript is the right way to go.

Here is my html/view of the TextBox which contains the integer.

        <div class="form-group">
        @Html.LabelFor(model => model.UnitsOrdered, (string)"Units Remaining ", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBox("Remaining", null, new { @class = "form-control", Value = ViewBag.Total, @readonly = "readonly" })
        </div>
    </div>

If "Remaining" is less than zero, I would like the font text in "Remaining" to be red and bold. I would also like to make the dropdown "CheckOpen" to become Locked or ReadOnly. (This will prevent users from processing an order when the balance is negative)

I am lost with JScript as to how to control the attributes of the html objects and how to find them by id.

I assume I would need to do this in document.ready . . . as I want this to happen immediately after page loads.

            <!-- Begin JScript for negative balance-->
            <script>
            $( document ).ready(function() {

             });

            </script>
        <!-- End JScript for Negative Balance-->

With the help from the comments (below), I was able to accomplish what I needed.

I added some css styles here:

<style>
.pos {
    color: black;
    font-weight: normal;
}

.neg {
    color: red;
    font-weight: bold;
}

And this was my final Jscript that worked

            <!-- Begin JScript for negative balance-->
            <script>
                $(document).ready(function () {

                    var remaining = $('#Remaining').val();


                    if (remaining > -1) {
                        $("#Remaining").addClass("pos");
                        $('select[name=CheckOpen]').prop('disabled', false);

                    } else {
                        $("#Remaining").addClass("neg");

                        $('select[name=CheckOpen]').prop('disabled', true);

                    }                                   
             });

            </script>
        <!-- End JScript for Negative Balance-->

With this, The text turns red and bold if the int is less than 0, and disables the additional dropdown. If the int is 0 or greater, the text remains black, and the additional dropdown remains enabled.

Thank you!!!

0 个答案:

没有答案