Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1598 How can I pass text to a function and have it change the selection of a select box to the option which has that text as its value?

irt.org | Knowledge Base | JavaScript | Form | Q1598 [ previous next ]

Q1598 How can I pass text to a function and have it change the selection of a select box to the option which has that text as its value?

Try the following for a single select list:

<form name="myForm">
<select name="mySelect">
<option>abc
<option>xyz
<option>abc
<option>xyz
<option>abc
<option>xyz
<option>abc
<option>xyz
</select>
</form>

<script language="JavaScript"><!--
function selectIt(txt) {
  theSel = document.myForm.mySelect;
  for (i=0;i<theSel.options.length) {
    if (theSel.options[i].text == txt) {
      theSel.selectedIndex = i;
      break;
    }
  }
}
//--></script>

And the following for a multiple select list:

<form name="myForm">
<select name="mySelect" multiple size="3">
<option>abc
<option>xyz
<option>abc
<option>xyz
<option>abc
<option>xyz
<option>abc
<option>xyz
</select>
</form>

<script language="JavaScript"><!--
function selectIt(txt) {
  theSel = document.myForm.mySelect;
  for (i=0;i<theSel.options.length) {
    if (theSel.options[i].text == txt) {
      theSel.options[i].selected = true;
    }
  }
}
//--></script>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 6th July 2009. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2009 irt.org, All Rights Reserved.