1

I want to change the select option selected to another value. I.e.,

 <select id="myid"> 
<option value="1" selected="selected">1 </option>
<option value="2" >2 </option>
<option value="3" >3 </option>
<option value="4" >4 </option>
</select>

I have to trigger a change in this select and select the 3rd option I have the value how can I do it.?

I am adding an option each time by a function and I want after each addition of the option, I want it to be selected to do further activities.

Kara
  • 6,115
  • 16
  • 50
  • 57
Devan
  • 172
  • 1
  • 6
  • 15

3 Answers3

2

To change by index

<input type="button" value="Change Select" onclick="changeSelect(3)" />

function changeSelect(x) {
    document.frm.myid.selectedIndex = x-1;
}

to change by value

<input type="button" value="Change Select" onclick="changeSelect1(3)" />

function changeSelect1(x) {
  var myid = document.getElementById('myid');
  var st = myid.options;
  for(var i=0; i<st.length; i++) {
    if(st[i].value == x) {
      myid.selectedIndex = i;
    }
  }
}

Mr. Black
  • 11,692
  • 13
  • 60
  • 85
  • can i use the jquery trigger function to change by passing the option value?? – Devan May 10 '11 at 09:27
  • 1
    Yes, of-course. please see the link http://stackoverflow.com/questions/496052/jquery-setting-the-selected-value-of-a-select-control-via-its-text-description – Mr. Black May 10 '11 at 10:38
1
function Change() {
            for (i = 0; i < document.getElementById('ddStream').options.length; i++) {
                if (document.getElementById('ddStream').options[i].value == 1)
                document.getElementById('ddStream').selectedIndex = i;
            }
            alert(document.getElementById('ddStream').selectedIndex);
            return false;
        }

<select id="ddStream" onchange="return Change()">
                            <option value="">EEE</option>
                            <option value="">ECE</option>
                            <option value="">CSE</option>
                            <option value="1">E&I</option>
                        </select>

This is the basic syntax.. The other things that you have mentioned will go by the logic u write.. Eg, to select the last option that u add dynamically, document.getElementById('ddStream').selectedIndex = document.getElementById('ddStream').options.length -1

Raghav
  • 2,890
  • 7
  • 36
  • 56
0

selected="selected" selects the option you want, just put it on the 3rd option tag

E.g.

<select id="myid"> 
  <option value="1">1 </option>
  <option value="2">2 </option>
  <option value="3" selected="selected">3 </option>
  <option value="4">4 </option>
</select>
Michal Ciechan
  • 13,492
  • 11
  • 76
  • 118
  • actually i am adding an option each time and i want it to be selected .The way you are showing is not possible – Devan May 10 '11 at 09:29