1

I'm not a front-end developer and I'm trying to create a select box and add its options totally dynamically using Javascript and jQuery.

I'm almost there but I am having a problem adding each new select to the div block (the number of selects is different at different times).

So far, I can either get the last select created in the following code displayed (but without span tags)

$('#meeting-eft-time-unit-data').append('<span>').html(se).append('</span>');

or I just get the following list ...

$('#meeting-eft-time-unit-data').append('<span>' + se + '</span>');
object HTMLSelectElement][object HTMLSelectElement][object HTMLSelectElement][object HTMLSelectElement][object HTMLSelectElement]

Here's the code:

$.each(event_type_time_units,
 function(index, optionData) {
   var se = document.createElement("select");
   // give it a  name from 'name'
   se.name = 'eft[' + optionData.name + ']';
   // populate it from 'range_from .. range_to
   for(var i=optionData.range_from; i <= optionData.range_to; i++) {
     var option = new Option(i, i);
     if ($.browser.msie) {
       se.add(option);
     } else {
       se.add(option,null);
     }
   }

   // add display name to a label in a div block
   $('#meeting-eft-time-unit-headers').append('<span>' + optionData.display_name + '</span>');

   // add select to a div block
   /**
   This gives me the a good select but only the last one processed is displayed
   $('#meeting-eft-time-unit-data').append('<span>').html(se).append('</span>');
   or
   This gives the text as explained above
   $('#meeting-eft-time-unit-data').append('<span>' + se + '</span>');
   **/
 });

1 Answer 1

1

Try:

$('#meeting-eft-time-unit-headers').append($('<span/>').append(se));
Sign up to request clarification or add additional context in comments.

3 Comments

That's brilliant. Thank you. Is that a shortcut and if so, is there a beginner's way to write it?
No it's not really a shortcut (in fact there's probably a shorter way). $('<span/>') creates a span DOM element - I've never seen any jquery where you have to specifically add the start and end tag. Append is about appending elements, not text.
@ants - you might want to click the tick next to the answer - it helps with your '%accepted' score ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.