Reputation: 1674
I have a working MVC application which consist of two listboxes and buttons to various things to the listbozes. All of my jQuery functions in the following script execute correctly except for MoveUp and MoveDown which are never called (set breakpoints). The F12 Console is clean and there are no JavaScript errors. The two buttons in question are:
<button type="button" id="up" onclick="MoveUp()">Up</button>
<button type="button" id="down" onclick="MoveDown()">Down</button>
The jQuery code is as follows. Does the MoveUp and MoveDown functions need to be inside the "global" function?
<script src="~/Scripts/jquery-2.1.1.js"></script>
<script>
$(function () {
$("#add").click(function () {
$("#listBoxAvail > option:selected").each(function () {
$(this).remove();
val = $(this).val();
temp = $(this);
temp.val('L' + val)
$(temp).appendTo("#listBoxSel");
});
});
$("#remove").click(function () {
$("#listBoxSel > option:selected").each(function () {
$(this).remove().appendTo("#listBoxAvail");
});
});
$("#remove-all").on("click", function(event) {
$('#listBoxSel option').prop('selected', true);
$("#remove").trigger("click");
});
$("#select-all").on("click", function(event) {
$('#listBoxAvail option').prop('selected', true);
$("#add").trigger("click");
});
});
function MoveDown() {
var selectedOption = $('#listBoxSel > option[selected]');
var nextOption = $('#lstBoxSel > option[selected]').next("option");
if ($(nextOption).text() != "") {
$(selectedOption).remove();
$(nextOption).after($(selectedOption));
}
}
function MoveUp() {
var selectedOption = $('#lstBoxSel > option[selected]');
var prevOption = $('#lstBoxSel > option[selected]').prev("option");
if ($(prevOption).text() != "") {
$(selectedOption).remove();
$(prevOption).before($(selectedOption));
}
Upvotes: 2
Views: 72
Reputation: 33870
You're saying that "MoveUp and MoveDown are never called ", but the "console is clean and there are no JavaScript errors." That does mean the function is being called, else, you would see an error undefined is not a function
.
So, with that information, we can guess the error is in your function. Since you use jQuery, when the jQuery object is empty, it will fail silently (no error).
I don't have access to your HTML, so i am only guessing here, but you are using a select element and use this selector option[selected]
. You are probably trying the get the selected element but this does not do what you want. It select the option
that has the attribute selected
. Your HTML probably doesn't have it.
What you want to use is :selected
: It will get the selected option. Use that :
function MoveDown() {
var selectedOption = $('#listBoxSel > option:selected');
var nextOption = selectedOption.next("option");
if ($(nextOption).text() != "") {
$(selectedOption).remove();
$(nextOption).after($(selectedOption));
}
}
Upvotes: 2