Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/JS: How to change option value of select type using JS

I've been trying to figure out how to set a value to a an option in a select type. But no matter how much I try to understand I just can't (feels ashamed)..

So I was hoping that you guys could help me since you've helped me so many times before.. :)

Let's say we have:

<select name="box" id="test">    
<option value='tval'>Content</option>

shouldn't this next code change the text from 'Content' to 'box'?

function changeContent(form){
form.document.getElementById('test').options['tval'].value = 'box';
}

or am I completely wrong here? I've looked up so many different articles but no one could help me understand how to do this..

Thanks guys!

like image 302
DoobyScooby Avatar asked Jan 03 '12 17:01

DoobyScooby


People also ask

How do I change selection options in HTML?

We can change the HTML select element's selected option with JavaScript by setting the value property of the select element object. We have a select drop down with some options and 2 buttons that sets the selected options when clicked. We get the 2 buttons with getElementById .


4 Answers

If You need to change the text rather than the value;

function changeContent(){
     document.getElementById('test').options[0].text = 'box';
}

To set both the value and text;

function changeContent(){
     var opt= document.getElementById('test').options[0];
     opt.value =  'box';
     opt.text = 'box';
}
like image 129
Richard A Avatar answered Nov 02 '22 22:11

Richard A


No, value is the actual value of the option element, what will be sent when the user submits the form. What you are trying to access is the HTML of the option element, you would have to access it with something like:

form.document.getElementById('test').options['tval'].innerHTML='box'
like image 26
Heldraug Avatar answered Nov 02 '22 23:11

Heldraug


That will change the value from 'tval' to 'box'

I think what you are looking for is the inner text of the option.

W3CSchools.com has an example of what you are looking for in javascript. You did want javascript, correct?

http://w3schools.com/js/tryit.asp?filename=try_dom_option_settext

like image 42
PAULDAWG Avatar answered Nov 03 '22 00:11

PAULDAWG


Drop the form. part and use:

document.getElementById('test').options[0].innerHTML = 'box'; 

See http://jsfiddle.net/hMqFE/

like image 41
nav Avatar answered Nov 02 '22 23:11

nav