Reputation: 59
In my ASP.NET MVC application, I have a javascript file which has a jquery function in a javascript file under the Scripts folder. The function listens to drop down click event and fills the textbox with the selected value like below, but when I click the drop down option, this method doesn't get called and the value is not set in the text box. When I run with debugger (F12), if I paste the function in the debugger command line then clicking the drop down works!!!! Not sure why the method is not registered from the javascript file. The dropdown-menu and input text box are created using bootstrap input-group. The drop down is initially empty and filled by reading from a file in setup() function.
// In test.js
var testMap = {}
$(function () {
$("#dropdownlistId li a").click(function () {
var name = $(this).text();
$("#textBoxId").val(name);
});
});
function setup() {
// Read name and value pair in testMap
...
// Append names to drop down list
$.each(testMap, function (key, value) {
$("#dropdownlistId").append("<li> <a tabindex=\"-1\" href=\"#\"> " + key + "</a> </li>");
});
}
$(document).ready(function () {
setup();
});
In my cshtml file, I am calling the javascript file like:
@section Scripts {
@Scripts.Render("~/scripts/test.js")
}
<div class="col-md-3">
<div class="input-group">
<input id="textBoxId" type="text" class="form-control" placeholder="Enter name" />
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul id="dropdownlistId" class="dropdown-menu pull-right"></ul>
</div>
</div>
</div>
Upvotes: 0
Views: 758
Reputation: 7356
You are running into an issue where you're trying to bind to elements that do not yet exist. The ul#dropdownlistId
exists statically in the page template, but the li
's and their children are populated after the DOM Ready (via your setup function). You can change the binding to be bound to the element that always exists (ul#dropdownlistId
) and only act on certain child elements (li a
):
$(function () {
$('#dropdownlistId').on('click', 'li a', function () {
$('#textBoxId').val($(this).text());
});
});
Upvotes: 3