Geo
Geo

Reputation: 3200

Get all elements of a select tag

I have two select-multi lists and I want to get all the elements of the right list regarding if they are selected or not.

Just to give you an idea of what is going on visit my code in jsFiddle

You will see that I get back only data that are selected which is not ideal for what I am trying to do which is submit the form with all the elements of the right select list.

Note: The $('.submitForm').click(function (e)) MUST stay the same. I could create a new function to do that and then call the $('.submitForm').click(function (e)) but this will create an extra step in the process.

So my question really is if I can somehow get all the data from the right select box without having to create a new function just for this form. and without altering $('.submitForm').click(function (e)) which is being used by 8 different forms.

Update On a second thought, I don't think I can call the $('.submitForm').click(function (e)) from a new function so that will create an extra issue

Upvotes: 1

Views: 87

Answers (2)

RobG
RobG

Reputation: 147403

Just a comment:

You can replace all of this:

var increment = -1;
if (direction == 'up') increment = -1;
else increment = 1;
if ((selIndex + increment) < 0 || (selIndex + increment) > (listbox.options.length - 1)) {
    return;
}
var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text
listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;
listbox.selectedIndex = selIndex + increment;

with

var newIndex = selIndex + (direction == 'up'? -1 : 2);
if (newIndex > -1 && newIndex < listbox.length + 1) {
  listbox.insertBefore(listbox.options[selIndex], listbox.options[newIndex]);
}

and also all of this:

var newOption = document.createElement("option");
newOption.value = option.value;
newOption.text = option.text;
newOption.selected = true;
try {
  dest.add(newOption, null);
  src.remove(count, null);
} catch (error) {
  dest.add(newOption);
  src.remove(count);
}

with:

dest.appendChild(option);
option.selected = true;

Also, you shouldn't declare variables inside blocks. There is no block scope in javascript, so better to declare variables at the top of the function (except for loop counters declared in for statements).

Upvotes: 1

mambrow
mambrow

Reputation: 475

Add an onclick event to your 'Save' button:

<button type="button" class="btn btn-success submitForm" onclick="listbox_selectall('d', true);">Save</button>

This will be called before your jQuery event listener.

Upvotes: 3

Related Questions