Click to See Complete Forum and Search --> : Adding an option


Webskater
02-06-2003, 12:12 PM
Can anyone tell me the syntax for adding a new option at the bottom of a select list. Thanks.

function addoption()
{
Add an option to select box called Contact
Populate the value for this new option
Populate the text for this new option
}

<select name=Contact>
<option value=1>Fred</option>
<option value=2>Jim</option>
</select>

khalidali63
02-06-2003, 12:14 PM
listBox.options[index].value="value"
listBox.options[index].text="text"

cheers

Khalid

Webskater
02-06-2003, 12:26 PM
Thanks Khalid.
I tried your suggestion and it came back with 'index is undefined'.

I tried this:
opener.document.JobForm2.Name.options[opener.document.JobForm2.Name.selectedIndex].text = 'Arthur' and it replaces the last option in the select box instead of adding one to the bottom of the list.

khalidali63
02-06-2003, 12:56 PM
the code sample I posted will put new option with value and text.you'll have to determine the last listBox index and then put the new value there.

Khalid

Webskater
02-06-2003, 02:43 PM
function AddRow()
{
listBox.options[index].value="value"
listBox.options[index].text="text"
}

Hi, Khalid
Taking your code above I created this.
<select name=listBox onchange=AddRow()>
<option value=1>Fred</option>
<option value=2>Bill</option>
</select>
If I hardcode your code like this:
listBox.options[0].value="3"
listBox.options[0].text="Jack"
it replaces the first item in the select list.

If I hardcode your code like this:
listBox.options[1].value="3"
listBox.options[1].text="Jack"
it replaces the second item in the select list.

If I hardcode your code like this:
listBox.options[2].value="3"
listBox.options[2].text="Jack"
It does not appear to be creating a new option because I get the errror "listBox.options.3 is not an object". Any idea what I am doing wrong?
Thanks.

khalidali63
02-06-2003, 07:04 PM
Ok I think I know what your talking about.

here check this out..its not optimised in anyways at all..:-)

Khalid

Webskater
02-07-2003, 03:38 AM
Thanks for that Khalid. I'll try that. In the meantime I have tried:
optionName = new Option('Jim',1,true,true)
listBox.options[listBox.selectedIndex + 1] = optionName
listBox.options[listBox.selectedIndex].value = 40
listBox.options[listBox.selectedIndex].value = 'Jenny'

It works if its all on the same page. But trying to add the option from another page creates a "server threw an exception" message. Any ideas?