Reputation: 30604
I've got this code from an example I found useful around Internet. It uses two listboxes one in the left the other in the right and it passes an element in the left one to the right one and viceversa. This is the HTML with a select with options:
<select id="SelectLeft" multiple="multiple">
<option value="1">Stack Overflow</option>
<option value="2">Server Fault</option>
<option value="3">Ask Ubuntu</option>
<option value="4">Super User</option>
</select>
<button id="MoveRight"> >> </button>
<button id="MoveLeft"> << </button>
<select id="SelectRight" multiple="multiple"></select>
This is the JavaScript to move the elements between the listboxes:
$(function() {
$("#MoveRight,#MoveLeft").click(function(event) {
var id = $(event.target).attr("id");
var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
var selectedItems = $(selectFrom + " :selected").toArray();
$(moveTo).append(selectedItems);
selectedItems.remove;
});
});
As you can see, the code just determines which selected elements must be appended and removed according to the button pressed. I need to detect when the listbox on the right ("SelectRight") has no options. For example at the very beginning when nothing has been pressed or if the user removes all the items.
I need a way to detect this so I can trigger a validation process I have.
Thanks for your answers, I've found that $("#SelectRight").is(":empty")
seems to be what I need. However the behavior it's not what I need. I need an event to be launched every time the listbox it's emptied. For example if I do this:
if($("#SelectRight").is(":empty")) alert("It works?? =O");
This alert it's only displayed when the page loads, BUT if I add and then remove the element, it doesn't triggers anymore. So I guess I need to add an event handler or something. Maybe a JQuery .on()
or something??
Upvotes: 2
Views: 3526
Reputation: 521
why not just add an if statement checking if the list box is emptied. I would put it after the selectedIteams.remove, this will check it every time the function is called to change the list box which is what will empty it. or you could add a onchange = 'someFunction()' function to your element and check every time the element changes.
Upvotes: 0
Reputation: 207901
How about:
$("#MoveRight,#MoveLeft").click(function(event) {
var id = $(event.target).attr("id");
var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
var selectedItems = $(selectFrom + " :selected").toArray();
$(moveTo).append(selectedItems);
selectedItems.remove;
if($('#SelectRight option').length<=0) console.log('Right empty');
});
Upvotes: 3
Reputation: 87073
$('#SelectRight option').length:
or
$('#SelectRight').is(':empty');
Upvotes: 4