最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set variable value from input before submit - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Sep 15, 2022 at 7:50 SuperStormer 5,4275 gold badges28 silver badges39 bronze badges asked Jan 18, 2012 at 6:06 user1104092user1104092 1
  • Does this answer your question? Get selected value/text from Select on change – SuperStormer Commented Sep 15, 2022 at 7:51
Add a ment  | 

4 Answers 4

Reset to default 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>

Declare a onchange event handler.

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

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>

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
发布评论

评论列表(0)

  1. 暂无评论