admin管理员组

文章数量:1287525

I want to change the value of value using a change event listener. Is it possible? Here is my sample code:

<select name="select1" onchange="updatevariable(this.value)"> 
    <option value="2" >2</option>
<option value="15" >15</option> 
</select>
<script type="text/javascript">
    value = "test";
    function updatevariable(data) { 
        value = data;       
    }
    alert(value); // It should be 2/15
</script>

I want to change the value of value using a change event listener. Is it possible? Here is my sample code:

<select name="select1" onchange="updatevariable(this.value)"> 
    <option value="2" >2</option>
<option value="15" >15</option> 
</select>
<script type="text/javascript">
    value = "test";
    function updatevariable(data) { 
        value = data;       
    }
    alert(value); // It should be 2/15
</script>
Share Improve this question edited Sep 24, 2011 at 10:00 Marek Sebera 40.7k37 gold badges164 silver badges249 bronze badges asked Sep 24, 2011 at 9:28 no_freedomno_freedom 1,96110 gold badges30 silver badges48 bronze badges 10
  • What is the problem? What doesn't work? – Pekka Commented Sep 24, 2011 at 9:29
  • 2 The alert is executed before you make any change to the select field (at the time when you assign value = "test"; and define updatevariable, not when you call updatevariable). Put it inside the event handler. – Felix Kling Commented Sep 24, 2011 at 9:31
  • what is the issue. it seems to be working fine jsfiddle/JmpSU – Mridul Kashatria Commented Sep 24, 2011 at 9:32
  • @Pekka When I run this code. Its display alert hello. Not 2/15 – no_freedom Commented Sep 24, 2011 at 9:32
  • @mridkash it is not working on that fiddle, read question again – Marek Sebera Commented Sep 24, 2011 at 9:32
 |  Show 5 more ments

1 Answer 1

Reset to default 7

You have alert() in wrong place

<select name="select1" onchange="updatevariable(this.value)"> 
    <option value="2" >2</option>
    <option value="15" >15</option> 
 </select>
 <script type="text/javascript">
    var value = "test";
    function updatevariable(data) { 
        value = data;
        alert(value);
    } 
 </script>

In your code it is loaded right after the script is loaded,
you have to modify it to be called right after change

本文标签: javascriptChange variable value using onchangeStack Overflow