简体   繁体   中英

jquery function firing even though condition is false

This is a real mystery for me and the other developers who have looked at it. I have a jquery function and within the function I have an if statement. There is some code within the statement body that I want executed when the condition is true, but not executed when the condition is false. Pretty simple. However, the code within the body is being executed, EVEN when the condition is false. The variable in the condition is called delayExists (which is outside the function). I tested using a variable (called test) within the function and "forced" the condition to be true - ONLY in this scenario is the if statement working correctly. I've stepped through the code using Chrome Developer tools and can see when delayExists becomes true yet the condition appears to be ignored. I've tried to include the pertinent code below. Please let me know I need to provide more.

<!-- at model specifies the type of object the view expects -->
@model atdaem
<div class="tab-pane" id="tab_delays">
    <div class="row">
        <div class="col-xs-12">
            @(Html.Kendo().Grid<atdlm>().Name("delays-grid").Columns(columns =>
              {
                  columns.Bound(c => c.Id).HeaderTemplate(" ").Width(1).ClientTemplate("<span style=\"white-space:nowrap;\">" + "<button type=\"button\" class=\"btn btn-social-icon btn-linkedin\" " + "data-toggle=\"modal\" data-target=\"\\#delayAddModal\" data-guid=\"#=Id#\" data-name=\"#=LocationName#\" " +

                                                                                       "data-title=\"Edit Delay\" >" + "<i class=\"fa fa-edit\"></i></button>" + "</span>");
                  ;
              }).DataSource(dataSource => dataSource
                                              .Ajax()
                                              .Read(read => read.Type(HttpVerbs.Post)
                                                                .Action("ActualDelayList", "TrainActivity")
                                                                .Data("actualJobTaskId")))
              .Events(events => events.DataBound("delaysDatabound")))
            <div class="pull-right top-buffer">
                <button type="button" class="btn bg-green" data-toggle="modal"
                        data-title="Add Delay"
                        data-target="#delayAddModal">
                    <i class="fa fa-plus-square"></i>
                    Add delay
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="delayAddModal" tabindex="-1" role="dialog" aria-labelledby="delayAddLabel">
    <div class="modal-dialog" role="document">
        <!-- Modal content -->
        <div class="modal-content">
            <div class="modal-header">
                <!-- This "x" button is for dismissing the modal -->
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="delayAddLabel">Add Delay</h4>
            </div>
            <div class="modal-body">
<form name="delay-form" id="delay-form">
    @Html.HiddenFor(m => m.atdId, new { id = "atdId" })

    @Html.HiddenFor(m => m.ajtId)

    @*Original:*@
    <div class="form-group">
        <!-- Renders floating text ("Subdivision") above the select options -->
        @Html.LabelFor(m => m.SubdivisionId, new { @class = "field-label always-visible" })

        <!-- ID for select element -->
        <!-- Renders select class="select" id="SubdivisionId" name="SubdivisionId"><option value="4429faa8-5ad4-4adf-adde-ec7cf88ed9e9" innerHTML "Caltrain"-->
        @Html.DropDownListFor(m => m.SubdivisionId, Model.AvailableSubdivisions, new { @class = "select" })
        @Html.ValidationMessageFor(m => m.SubdivisionId)
    </div>

    <div class="row">
        <!--Start milepost -->
        <div class="col-xs-6">
            <div class="form-group">
                @Html.LabelFor(m => m.StartMilepost, new { @class = "field-label" })
                @Html.TextBoxFor(m => m.StartMilepost, new { @class = "form-control", placeholder = Html.DisplayNameFor(m => m.StartMilepost) })
                @Html.ValidationMessageFor(m => m.StartMilepost)
            </div>
        </div>
        <!-- End milepost -->
        <div class="col-xs-6">
            <div class="form-group">
                @Html.LabelFor(m => m.EndMilepost, new { @class = "field-label" })
                @Html.TextBoxFor(m => m.EndMilepost, new { @class = "form-control", placeholder = Html.DisplayNameFor(m => m.EndMilepost) })
                @Html.ValidationMessageFor(m => m.EndMilepost)
            </div>
        </div>
    </div>
    <!-- Location -->
    <div class="form-group">
        @Html.LabelFor(m => m.LocationId, new { @class = "field-label always-visible" })
        <select id="LocationId" name="LocationId" class="select">
            @foreach (var loc in Model.AvailableLocations)
            {
                <option value="@loc.Id" data-milepost="@loc.Milepost">@loc.Name</option>
            }
        </select>

        @Html.ValidationMessageFor(m => m.LocationId)
    </div>


</form>
</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <!-- call to js function-->
                <button id="delayAddButton" type="button" class="btn btn-primary" data-title="Add Delay">Add Delay</button>
            </div>
        </div>
    </div>
</div>

<script>

var delayExists = false;

    //the jquery function is listening for the element with the id #delayAddModal (which is also used for delayEdit); when that modal is shown (by someone clicking
    // on the Add Delay button which has a data-target that points to the modal), just before the modal appears this fuction executes)
    $("#delayAddModal")
        .on("show.bs.modal",
            function(event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var modal = $(this);
                var title = button.data('title'); // get New title from data-title attribute
                var delId = button.data("guid");
                var name = button.data("name");

                var conditionalVariable = 1;

                var updateButtonValue = "Save Edit";


                modal.find('.modal-title').text(title); // set title to New title
                modal.find('#delayAddButton').text(updateButtonValue); // set button value to Edit Delay


                $.ajax({
                    type: "GET",
                    url: "/TrainActivity/GetDelayDataForEditing/" + "?delayId=" + delId,
                    dataType: 'json',
                    success: function(data) {

                        delayExists = true;
                        modal.find('');

                        var sub = data.SubdivisionId;

                        $.getJSON('/TrainActivity/LocationBySubdivisionList?id=' + sub,
                            function(locs) {

                                // the stuff that needs to happen before the parent ajax completes needs to go in here
                                $('select#SubdivisionId').val(data.SubdivisionId).trigger('change');


                                $('#StartMilepost').val(data.StartMilepost);
                                $('#EndMilepost').val(data.EndMilepost);
                                $('#LocationId').val(data.LocationId).trigger('change');
                                //$('select#LocationId').val(data.LocationId).trigger('change');
                            });

                    },
                    error: function() { alert("error in Delay Edit"); }
                });


            });

    //matches location based on input in Start Milepost
    $(document)
        .ready(function() {
            var test = true;
            //matches location based on input in Start Milepost
            var button = $(event.relatedTarget); // Button that triggered the modal
            var delId = button.data("guid");
            if (test == false) {
            //if (delayExists == false) {
                $("#StartMilepost").change(function() {
                    $("#EndMilepost").val($(this).val());
                    //nearestMilepost();

                });
            }
            @*function nearestMilepost()
            {
                //var mile = parseFloat($(this).val());
                var mile = $("#@Html.IdFor(m => m.StartMilepost)").val();
                var sub = ($("#SubdivisionId").val());

                var locationId = $('#LocationId option').filter(function () {
                    return parseFloat($(this).data('milepost')) >= mile
                }).val();

                $("#LocationId").val(locationId).change();
            }



        });
            //changing the subdivision changes the locations available in the location box
            @*$("#SubdivisionId").change(function () {
                var sub = $(this).val();

                $.getJSON('@Url.Action("LocationBySubdivisionList", "TrainActivity")?id=' + sub,
                    function (locs) {
                        var list = $('#@Html.IdFor(model => model.LocationId)');
                        list.find('option').remove();
                        $(locs).each(function (index, loc) {
                            list.append('<option value="' + loc.Id + '" data-milepost="'+ loc.Milepost+'">' + loc.Name + '</option>');
                        });
                        nearestMilepost();
                    });

            });*@
        });
</script>

The misunderstanding is here:

if (delayExists == false) {
  $("#StartMilepost").change(function() {
    $("#EndMilepost").val($(this).val());
    // etc.
  });
}

That check happens once , at startup. Is delayExists false? Yes (at startup), so we add that handler. Which will always run all of the code within.

If you want to check the flag everytime #StartMilepost changes, you need to do that:

$("#StartMilepost").change(function() {
  if (delayExists == false) {
    $("#EndMilepost").val($(this).val());
    // etc.
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM