-1

I have a select in HTML, which is dynamically generated.

When the page loads, I want to make the select box have a variable default option on page load, without having to change the order of the select list.

I cannot make this work by setting the value attribute when I dynamically generate the page. It is always the top value that is visible, regardless of the value property.

I would also like to be able to change this via jQuery after the document has been loaded.

Is this possible?

<select class="form-control input-lg" tabindex=1 id="instrument-select" 
                      name="instrument" value="<?php echo $instrument->slug; ?>">
    <?php foreach ($instrument_list as $instrument): ?>
        <option value="<?php echo $instrument['slug']; ?>">
                              <?php echo $instrument["name"]; ?>
        </option>
    <?php endforeach; ?>
</select>
iamyojimbo
  • 4,233
  • 6
  • 32
  • 39

2 Answers2

3

I think you just need to do this

<select class="form-control input-lg" tabindex=1 id="instrument-select" name="instrument">
    <?php foreach ($instrument_list as $instrument): ?>
        <option value="<?php echo $instrument['slug']; ?>" <?php echo $instrument->slug==$instrument['slug']?'selected="selected"':''; ?>><?php echo $instrument["name"]; ?></option>
    <?php endforeach; ?>
</select>


never add value attribute to select it should be there on every individual option and only need to make selected to required option.

Ramesh Mhetre
  • 404
  • 2
  • 12
1

When you dynamically create the select html, add the 'selected' attribute to the option element you want selected;

<option value='firstOption'>firstOption</option>
<option value='someOption' selected>Some Option</option>  <!-- this one will be selected -->
<option value='thirdOption'>thirdOption</option>
Nick M
  • 1,647
  • 13
  • 17