Function not executing with a handler defined inside another handler

The code in the JSFiddle) runs perfectly fine but not in my application code. Basically the control isn’t reaching inside the console.log inside the function checkSelection()

Here is my HTML::

    <b> Name Status:</b> <span id="name_status"></span>
<img src="https://dl.dropboxusercontent.com/u/41774950/pencil.png" alt="Name status" id="nameStatus">
<div id="name_status_popmodal_dialog" style="display:none;width:700px">
   <select class="form-control" id="name">
      <option value="First">First</option>
      <option value="Second">Second</option>
      <option value="Third">Third</option>
      <option value="Fourth">Fourth</option>
   </select>
   <div class="row">
      <div class="form-group col-sm-2" style="width:100px">
         <button class="btn btn-success  center-block" id="nameSave" data-popmodal-but="ok">Save</button>
      </div>
      <div class="form-group col-sm-2" style="width:100px">
         <button class="btn btn-success  center-block" id="nameCancel" data-popmodal-but="cancel">Cancel</button>
      </div>
   </div>
</div>
<div style="display:none">
   <div id="content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
      software like Aldus PageMaker including versions of Lorem Ipsum.
      <div class="popModal_footer">
         <button type="button" class="btn btn-primary" data-popmodal-but="ok">ok</button>
         <button type="button" class="btn btn-default" data-popmodal-but="cancel">cancel</button>
      </div>
   </div>
</div>

Here is my Javascript from the previous code for proper understanding:

$("#nameStatus").click(function() {
    $('#nameStatus').popModal({
        html: $('#name_status_popmodal_dialog').html(),

        onOkBut: function() {

                var id_value;

                $('#name').on('change', checkSelection);

                var url = "// some URL here"


                // On change, show a dialog 
                $('#name').on('change', checkSelection);


                function checkSelection() {
                    var dropdownSelectionItem = $("#name").val();

                    console.log("Check:" + dropdownSelectionItem);

                    if (dropdownSelectionItem == "First") {
                        alert("Are you sure you want to select first option?");
                        id_value = 1000;
                    } else if (dropdownSelectionItem == "Second") {
                        id_value = 2000;
                    } else if (dropdownSelectionItem == "Third") {
                        alert("Are you sure you want to select third option?");

                        $('#content').confirmModal({
                            topOffset: 0,
                            onOkBut: function() {
                                id_value = 3000;
                            },
                            onCancelBut: function() {},
                            onLoad: function() {},
                            onClose: function() {}
                        });

                    } else if (dropdownSelectionItem == "Fourth") {
                        id_value = 4000;
                    }
                }

                if (!isEmpty(id_value)) {

                    var ajaxRequest = jQuery.ajax({
                            data: {
                                id: id_value
                            },
                            dataType: "json",
                            method: "GET",
                            url: url
                        })
                        .done(function(data_, textStatus_, jqXHR_) {
                            // Something here
                        })
                        .fail(function(jqXHR_, textStatus_, errorThrown_) {
                            // Something here
                        });


                } else {

                    alert("Cannot Change Name Status! id_value is empty");
                }

            } // END of onOkBut function()


    }); // End of popModal function
}); // End of Click Handler

Problems:

The consolelog console.log("Check:" + dropdownSelectionItem); isn’t executing as the control isn’t reaching the checkSelection function. Hence, I am always getting the alert message in the else statement which isalert("Cannot Change Name Status! id_value is empty");

What’s wrong I am doing or missing?

Reference of PopModal jQuery plugin.

The flow is as follows:

  1. user clicks OK button
  2. add a change listener to #name
  3. check if id_value is set (which it is not)
  4. user may change #name and trigger checkselection

So you’ll have to pull the change listener outside the onOkBut handler and make id_value a global variable, so that checkSelection can be called before the modal actually opens. You’ll rarely want to bind listeners from within other event handlers anyway; such event-driven programs don’t necessarily run from top to bottom as the actual code.

var id_value
$('#name').change(function checkSelection() { /* ... */ })
$('#namestatus').click(function() {
  $(this).popModal({ /* ... */ })
})

@m3g4p0p Thanks for your reply. I actually tried the following as you suggested. However, I couldn’t see the control getting inside the function as console.log("Am I in change listner?"); isn’t executing. Am I doing anything wrong? Thanks



var id_value;
$('#name').change(function checkSelection()
  {
		console.log("Am I in change listner?");
		if (dropdownSelectionItem == "First") {
			  id_value = 1000;
		  } else if (dropdownSelectionItem == "Second") {
			 id_value = 2000;
		  } else if (dropdownSelectionItem == "Third") {
			  alert("Are you sure you want to select third option?");
			  id_value = 3000;
		  } else if (dropdownSelectionItem == "Fourth") {
			  id_value = 4000;
		  }

   })


$("#nameStatus").click(function() {
    $('#nameStatus').popModal({
        html: $('#name_status_popmodal_dialog').html(),

        onOkBut: function() {

                var url = "// some URL here"


				if (!isEmpty(id_value)) {

                    var ajaxRequest = jQuery.ajax({
                            data: {
                                id: id_value
                            },
                            dataType: "json",
                            method: "GET",
                            url: url
                        })
                        .done(function(data_, textStatus_, jqXHR_) {
                            // Something here
                        })
                        .fail(function(jqXHR_, textStatus_, errorThrown_) {
                            // Something here
                        });


                } else {

                    alert("Cannot Change Name Status! id_value is empty");
                }

            } // END of onOkBut function()


    }); // End of popModal function
}); // End of Click Handler

The console output works for me… here’s a fiddle. Note that dropdownSelectionItem is not defined though, so you might add something like

const dropdownSelectionItem = this.value

to the head of checkSelection.

Thanks @m3g4p0p . I was trying to plug in the same functionality in my JSFiddle(commented lines of code) which is using popModal library but it doesn’t work. Do you think I am defining the function at correct location? As far as I understood,It needs to be somewhere inside the html() as its responsible for showing the HTML content of the dialog.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.