开发者

Javascript selecting option from a select dropdown, using a href

开发者 https://www.devze.com 2022-12-10 19:50 出处:网络
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.

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="inputboxattri开发者_开发百科b" 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!


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>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消