1

First, I have this input in a form.

<select id="entry_14">
     <option value="Woman">Woman</option>
     <option value="Man">Man</option>
</select>

Then I declared this variable.

var mygender = document.getElementById('entry_14').value;

but then, when I document.write, it already shows "Man" before the user even makes a selection, and after selecting woman, it still shows man.

How can I set the value of this variable to change, each time the user selects one of the options?

1

4 Answers 4

5

It executes immediately because your code is not in a function. You need to call this function when the select changes. Add an onchange handler to your select. In this example I pass this.value which is your select lists value to the function. Finally you can do whatever you want with that value.

<select id="entry_14" onchange="myfunction(this.value);">
    <option value="Woman">Woman</option> 
    <option  value="Man">Man</option>
</select>

<script>
    function myfunction(val) {
        document.write(val);
    }
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

In IE, if the user is navigating the options using the cursor keys, the onchange listener will be called each time they press the up or down key.
mrtsherman, your solution works, now it writes the correct selected value, but... It replaces everything else on the page. When the user makes a selection, the entire form goes away, and "woman" is the only thing you see at the top left of the page. Can I document.write to another place in the same/original page, while keeping the form on screen? Thanks for your help!
Yes, you can modify an existing elements contents to relect the output. This is the preferred way. jsfiddle.net/eZg5h
3

Declare a onchange event handler.

document.getElementById('entry_14').onchange = function(){
    var mygender = this.value;
    document.write(mygender);
}

1 Comment

+1 - I actually like this answer better than my own because it doesn't rely on inline javascript declarations.
0

Add a onChange JS handler to the <select> element. The example below shows an inline way of doing this...

<select id="entry_14" onChange="updateMyGender();">
    ....
</select>

<script>
    var mygender = document.getElementById('entry_14').value;
    function updateMyGender()
    {
        mygender = document.getElementById('entry_14').value;
    }
</script>

Comments

0

I think you are looking for this

var mygender= document.getElementById('entry_14');
var gender= mygender.options[mygender.selectedIndex].value;// for value 

var gender= mygender.options[mygender.selectedIndex].Text;//for text

1 Comment

selectedIndex is only required to support ancient browsers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.