First of all, as you haven't mentioned whether you are planning on supporting legacy browsers or not, I've decided to add support for that browsers as well. My script works with all IE versions (IE7 inclusive).
So, first we attach our eventlistener to your select element. Then we retrieve the text of the selected option and return the value;
Have a look at this => DEMO
If you want to submit it via $_POST than do the following ->
- Create a
hidden input element, set its name attribute to say select, then set its value to the value of our text variable (we will have that variable when one of our options is selected) - See the code below.
- After submitting your form you can retrieve the value like so =>
$_POST['select'] (select is the name attribute we have assigned to our hidden input element)
Javascript
//attaching the eventlistener (modified the code to make it compatible with older IE versions)
function attach(element,listener,ev,tf){
if(element.attachEvent) {
//support for older IE (IE7 inclusive)
element.attachEvent("on"+listener,ev);
}else{
//modern browsers
element.addEventListener(listener,ev,tf);
}
}
function returnTextofTheSelectedElement(sel){
//getting and returning the text of the selected option
selectedIndex = sel[sel.selectedIndex];
return text = selectedIndex.innerText ? selectedIndex.innerText : selectedIndex.textContent;
}
var select = document.getElementById('region');
attach(select,'change',function(){
//pass the select tag you want to get the text of
//*returnTextofTheSelectedElement* function returns our text
alert(returnTextofTheSelectedElement(select));
//so you can store it in a *variable* and use it when submitting your form
text = returnTextofTheSelectedElement(select);
//if you want to submit it via $_POST than do the following
//create a hidden *input* element, set its name attribute to say *select*, then set its value to the value of our *text* variable
input = document.createElement('input');
input.type = 'hidden';
input.name = 'select';
input.value = text;
select.parentNode.appendChild(input);
alert('The value/text of the hidden input is '+input.value);
//when submitting the form, it will also submit out hidden input with the value (text) of the selected option
//you can retrieve the value like so => *$_POST['select']*
},false);
HTML
<select name='region' id='region'>
<option value='1'>Region 1</option>
<option value='2'>Region 2</option>
<option value='3'>Region 3</option>
<select>