views:

387

answers:

3

hello, I'm trying to append a select option list to a div table with jQuery, after done this, I'd like to select a specific option of the list, I'm trying something like this:

// my hidden option list
<div style="display:none;">
<select class="option_list">
    <option value="male">Male</option>
    <option value="female">Female</option>
    <option value="none">Unknown</option>
</select>
</div>

<div id="my_table">
    <div>
        <div>John</div>
        <div>25</div>
        <div></div>
    </div>
    <div>
        <div>Emy</div>
        <div>22</div>
        <div></div>
    </div>
    <div>
        <div>Sarah</div>
        <div>28</div>
        <div></div>
    </div>
</div>

// $(".option_list") is hidden in HTML page, I clone and append it to my div table row
$(".option_list")
      .clone ()
      .appendTo ("#my_table > div > div:last-child")
      .attr ("name", "a_dynamic_name_for_php_form")
      .find ("option[value=none]").selected = true;
A: 

You should write .val('none'). The val method will find the <option> with that value. (Or, failing that, that text)

SLaks
I've tried this but seem to set all the options to value 'none'
Vittorio Vittori
You of course need to do that on the `select` element, not on all `option` elements.
BalusC
+1  A: 

Try this:

$(".option_list")
  .clone ()
  .appendTo ("#my_table > div > div:last-child")
  .attr ("name", "a_dynamic_name_for_php_form")
  .find ("option[value=none]").attr("selected", "true");

Notice the change in the last line.

Felix
thanks for the help, it works
Vittorio Vittori
A: 

Why clone it? As simple as it may be, I would define hidden html parts as string and simply append them:

var add = '<select>' +
          '  <option value="one">one</option>' +
          '  <option two ... '+
          '</select>';
$(something).appendTo(add);

Bit dirty, but... :) - (you could even define those hidden parts with asp/php, so you don't have to write each line)

Edit: already answered...

Adam Kiss