Change select value on click with javascript
Apologies for so basic a question, but I can't find an answer anywhere. When the button is clicked, I need to change the value a select passes to the next page. I'm not trying to change the option list on this page, but rather trying to change the value which the select passes to the next page.
<form name="myform" action="test2.php" method="get">
<select name="selectname" id="selectid">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" onclick="document.getElementById('selectid').value='3';" />
</form>
I could 开发者_StackOverflow中文版easily change the passed value if it were an input rather than a select, but for some reason I am unable to get this to work with a select. Either a straight javascript or a prototype answer will work.
There is no option with the value 3 so document.getElementById('selectid').value='3';
will have no effect.
Setting the value for a <select>
way simply selects the option with the matching value. If that value doesn't exist, nothing happens. Is that what you're trying to do?
Edit
If what @JohnP suggested in his comment is what you're trying to achieve i.e. change the value
attribute for an <option>
, you could do this in a function that is invoked on click:
var s = document.getElementById('test'); //get the select element
var o = s.options[s.selectedIndex]; //get the option element that is selected
o.value='3'; //change it's value
//o.innerHTML = '3'; //optionally change the text displayed
精彩评论