0

Is it possible to add items to a select (list box) of html/php through jQuery or javascript when a specific action is triggered by another control in jQuery/javascript? (edited by Alex Thomas)

Community
  • 1
  • 1
Ahmad Farid
  • 14,398
  • 45
  • 96
  • 136

3 Answers3

2

Yes, you can add items on the client-side. For example:

// Get the raw DOM select element (first use jQuery
// to find it, then get the raw version via [0] 
var select = $("select[name=someField]")[0];

// Add the option
select.options[select.options.length] = new Option("Third Option", "3");

Live example

See also: How do you update all options of a select with jquery?

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

Yes, attach a suitable handler to the event of your choice. For example if you want to add new items when another control changes, you might use something like this:

$('#controller').change(function() {
    $('#child_select').append('<option>New option</option>');
});

Or alternatively, there are jQuery plugins available to make the drop down list dynamic based on the selection of another element.

a'r
  • 35,921
  • 7
  • 66
  • 67
1

You can use the: $('select').append('<option value="id" selected="selected">Text</option>'); method, via jQuery. You can call this a number of ways (and get your data via ajax, stored objects, etc).

If you can provide a little more information of what actions you want to trigger this, I can provide a better example.

Hope this helps.

TNC
  • 5,388
  • 1
  • 26
  • 28
  • 1
    Are you sure jQuery's `append` works correctly to add options to a select box, reliably cross-browser? The raw DOM version, `appendChild`, does not, but that doesn't mean jQuery doesn't make it work under-the-covers. – T.J. Crowder Feb 21 '11 at 13:03
  • I'll clarify my post, but thanks for pointing that out. appending html works, but appending new Option('id', 'value') doesn't - thanks for the eye. – TNC Feb 21 '11 at 13:05