Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.
edited tags
Link
Source Link
Charles Burns
  • 10.7k
  • 7
  • 68
  • 85

jQuery event fires once, then never again

I've been wrestling with a simple JQuery event handler for hours. My event handler fires exactly once, when the page loads, and never again no matter the event or the interaction with the select box. When deferred, the alert (when I have one) shows the first select option. When not, the alert is blank.

All I want is for the select box to load from AJAX and for a user choice to trigger another AJAX call.

HTML:

<select id="connection" name="Connection"></select> <div id="testme" style="background: #CCC; width:100%; height:50px;position:relative;color:red">testing</div> 

Javascript:

$(document).ready(function () { // Event handler. Tried as a separate function and as a parameter to $.on(...) function connectionSelected() { var str = $('#connection option:selected').text(); alert(str); $("#testme").text(str); } var $connectionSelect = $('#connection'); //$connectionSelect.selectmenu(); // Tried enabling/disabling // Tried this and all JS code inside and outside of $(document).ready(...) $.when( $.ajax({ dataType: "JSON", url: '@Url.Content("~/API/ConnectionHint")', // The AJAX call (using ASP Razor) works fine success: function(data) { // This function is always called and works var items = []; $.each(data, function(key, val) { items.push("<option value='" + key + "'>" + val + "</option>"); }); $connectionSelect.append(items.join("")); // Tried setting up the event handler here }, error: function() { $connectionSelect.html('<option id="-1">none available</option>'); } }) ).then(function() { //$("#connection option").blur(connectionSelected()).change(); $("#connection").on("change", connectionSelected()); }); }); 

Tried dozens of variations of the event handler, several events, inside and outside of a deferred.done and deferred.then, etc.. E.g.:

$connectionSelect.selectmenu({ change: function (event, data) { $('#connection').change(function () { var str = ""; $('#connection').each(function () { str += $(this).text() + "<br>"; }); $("#testme").text(str); }); } }); 

I usually write back-end code and am familiar only with portions of JQuery, and this is driving me crazy. I've looked more than 30 related question on SO and elsewhere, e.g.

Any ideas are appreciated.