What am I doing wrong in the calling a Javascript Function

abiodunajai 396 Reputation points
2023-07-06T21:56:22.0133333+00:00

Please I have been battling with an issue since yesterday. I have a view where I wanted to call a Javascript function and then thereafter display a modal view with data but the Drop Down selection is not just returning the value of the selected option, rather it returns NULL.

Kindly let me know how I should handle it, please.

My Razor View is pasted below.

                 <div class="form-group">
                    @Html.LabelFor(model => model.PolicyCode, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownListFor(model => model.PolicyCode, new SelectList(Html.CodeDropDownList(), "PolicyCode", "FullDescription", Model.PolicyCode), new { id = "PolicyCode", @class = "form-control input-sm" })
                        @Html.ValidationMessageFor(model => model.PolicyCode, "", new { @class = "text-danger" })
                    </div>
                </div>
              <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <button type="button" class="btn btn-primary" onclick="ShowReceiptScheduleDialog(this, 'PolicyCode');">Process</button>
                    </div>
                </div>


        <div class="row">
                <div class="col-md-12 col-sm-8 col-xs-12 col-xs-offset-0">
                    <div id="scheduleDialog" tabindex="-1" role="dialog" aria-labelledby="scheduleDialogLabel" aria-hidden="true" class="modal fade" data-backdrop="static" data-keyboard="false">
                        <div class="modal-dialog modal-lg" style="height:50vh; max-height:50vh; width:180vh; max-width:180vh; overflow-y: initial !important">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

                                    <h4 class="modal-title" id="scheduleDialogLabel">Process</h4>
                                </div>
                                <div class="modal-body" style="height: 600px; overflow-y: auto; ">
                                        @{Html.RenderPartial();}
                                    </div>
                                </div>
                                <div class="modal-footer">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

Javascript

@section scripts {
 var currentDropdown = $(e.relatedTarget).data('id');

        function ShowReceiptScheduleDialog(btn, policyCodeTagID) {
            var result = getScheduleID(policyCodeTagID, true);
            if (result == true) {
                $('#scheduleDialog').modal('show');
            }
        }
      
        function getScheduleID(currentDropdown, fromDialog) {
            var scheduleID = "";
            var ddid = document.getElementById(currentDropdown + "1");
            if (ddid != null) {
                var dp = document.getElementById(currentDropdown);
                if (dp == null) {
                    dp = document.getElementById(currentDropdown.replace(".", "_"));
                }
                scheduleID = dp.value;
                receiptName = dp.text;
            }
       }


    </script>
}
           

Thanking all in anticipation of your prompt assistance.

Best regards,

Abiodunajai

Microsoft 365 and Office | Development | Office JavaScript API
Developer technologies | ASP.NET | Other
Developer technologies | C#
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2023-07-07T13:31:26.1066667+00:00

    Learn how to use the Browser's dev tools to debug the JavaScript. The following link is for Chrome but all browser's have dev tools.

    Debug JavaScript

    Your original code is missing quotes around a string assignment which causes a JavaScript error when the page loads. The error is visible in the "Console" view within dev tools.

    var scheduleState = "@ViewBag.ScheduleDetailState" //Was missing quotes
    

    Once this bug is fixed the next error is "Uncaught ReferenceError: e is not defined" which Bruce explained above.

    I think you want the following logic which reads the select when the page loads.

            var alreadyCalled = false;
            var receiptName = '';
            var scheduleAlreadyCalled = false;
            var lastScheduleID = "";
            var scheduleState = "@ViewBag.ScheduleDetailState" //Missing quotes
            var currentDropdown = "";
    
            $(document).ready(function () {
               //get data-id attribute of the clicked element
                //var currentDropdown = $(e.relatedTarget).data('id');
    
                currentDropdown = $('#PolicyCode').val();
                console.log(currentDropdown);
    
            });
    

    The two bug fixes above should get you to a point where the Modal shows. Hopefully, this will get you past these bugs and you can work on the others.


2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-07-06T22:51:13.7333333+00:00

    you code is confusing

    // follow line is a runtime error as e not defined. so functions not defined
    var currentDropdown = $(e.relatedTarget).data('id'); 
    
            // policyCodeTagID = "PolicyCode" 
            function ShowReceiptScheduleDialog(btn, policyCodeTagID) {
                var result = getScheduleID(policyCodeTagID, true);
    
                // the function always return undefined 
                // not clear what true means
                if (result == true) {
                    $('#scheduleDialog').modal('show');
                }
            }
          
            // currentDropdown = "PolicyCode" fromDialog = true
            function getScheduleID(currentDropdown, fromDialog) {
                var scheduleID = "";
    
                // should return null as there is no <select> with id="PolicyCode1"
                var ddid = document.getElementById(currentDropdown + "1"); 
    
                // always null
                if (ddid != null) {
                    var dp = document.getElementById(currentDropdown);
                    if (dp == null) {
                        // no idea what this about currentDropdown = "PolicyCode"
                        dp = document.getElementById(currentDropdown.replace(".", "_"));
                    }
                    scheduleID = dp.value;
    
                    // while a select has a .value, it does not have a .text
                    // also receiptName is a global variable
                    receiptName = dp.text;
    
                    // most likely if dp was valid you wanted:
                    // but not sure what the use is anyway
                    var receiptName = dp.options[dp.selectedIndex].text;              
                }
    
                // the function return no value 
                // caller expects true, so what was the point of this function
           }
    
    
        
    

  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-07-07T22:12:40.3166667+00:00

    simple use dropdown value load content (assuming the loadReceiptScheduleDetails url works)

    
    function ShowReceiptScheduleDialog(ddid) {
       const id = (document.getElementById(ddid) || {}).value;
       if (!id) 
           alert("select id");
       else {
            const url = "@Url.Action("loadReceiptScheduleDetails","home")";
            $("#scheduleDetailsDiv").html("<i>Loading...</i>);
            $('#scheduleDialog').modal('show'); 
            $.getJSON(url, {policyType: id})
               .done(function(r) {
                  $("#scheduleDetailsDiv").html(r.Data);
               }).fail(function(xhr, status, error) {
                  $("#scheduleDetailsDiv").html("Load failed: " + error);
               });
       }
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.