views:

392

answers:

2

Hello,

Im working on a CMS website that creates form elements on the fly according to id and values. I need to select certain information out of these forms using a link.

For radio options and checkbox options I use this code: <a href="#" onclick="document.getElementById('RAL1').checked=true">1001</a> Which works fine. RAL1 is the id of radio I want to check. With the select the id needs to be follwed by the options and this is where Im having problems because it needs to select a value out of an ID.

The code the form creates is

<select id="Zinc_plated_field" class="inputboxattrib" name="Zinc_plated12">
  <option value="no">no</option>
  <option value="yes">yes (+€871.08)</option>
</select>

I've tried just about everything but no luck. Can anybody point me in the right direction?

Thanks!

A: 

Just about every browser supports the following statement to get the selected value ("no" or "yes"):

document.getElementById('Zinc_plated_field').value

For very old browsers you would have to use:

var sel = document.getElementById('Zinc_plated_field');
sel.options[sel.selectedIndex].value;


If you want to set the selected value, there are several ways to do it:

document.getElementById('Zinc_plated_field').value = 'yes';

or

document.getElementById('Zinc_plated_field').options[1].selected = true;

or

document.getElementById('Zinc_plated_field').selectedIndex = 1;

The two latter use the index of the option you want to set (one specifies which index is selected by setting the selectedIndex property of the <select> element, while the other sets the selected attribute of the <option> element to true.)

I can't say which is most cross-browser compatible off-hand, but if the first one doesn't work, just try the other two.

Blixt
AFAICS, he wants to set the value, not get it.
rjmunro
Ah, right, I updated my answer.
Blixt
The first setter example (`.value = 'yes'`) works in all browsers and is blazing fast. However if a matching `value` attribute is not present on one the `<option>` list it will fail **in IE** (all versions), even if there is a matching `text` attribute present.
Crescent Fresh
A: 

This works for me in Firefox & Safari:

<a href="#" onclick="document.getElementById('Zinc_plated_field').value = 'yes'">yes</a>
<a href="#" onclick="document.getElementById('Zinc_plated_field').value = 'no'">no</a>
rjmunro