1

I have fins this code to show dropdown value in a textbox. Actually when i select a value from dropdown in text box a value is show. How to modify to show option text insted value?

<select id="Ultra" onchange="run()">
    <!--Call run() function-->
    <option value="0">Select</option>
    <option value="8">text1</option>
    <option value="5">text2</option>
    <option value="4">text3</option>
</select>

<br>
<br>
TextBox1
<br>

<form>
    <input id="srt" placeholder="get value on option select" type="text">
    <br>
    TextBox2<br>
    <input id="rtt" onkeyup="up()" placeholder="Write Something !" type="text">
    <script>
    function run() {
        document.getElementById("srt").value = document.getElementById("Ultra").value;
    }

    function up() {
        //if (document.getElementById("srt").value != "") {
        var dop = document.getElementById("srt").value;
        //}
        pop(dop);
    }

    function pop(val) {
        alert(val);
    }
    </script>
</form>
Jeff Miller
  • 2,347
  • 1
  • 26
  • 40
user1504222
  • 269
  • 1
  • 10

2 Answers2

2

You need to get the text of the selected option, e.g.

<!-- pass reference to the element in the call -->
<select id="Ultra" onchange="run(this)">

script:

function run(sel) {
  var i = sel.selectedIndex;
  if (i != -1) {
    document.getElementById("srt").value = sel.options[i].text;
  }
}
RobG
  • 134,457
  • 30
  • 163
  • 204
0

var Select = document.getElementById("Ultra");

var selectedText = Select.options[Select.selectedIndex].text;

Zero Cool
  • 114
  • 1
  • 6
  • Note that if no option is selected, the `selectedIndex` will be -1. In that case, `Select.options[Select.selectedIndex]` will return `undefined`, which doesn't have a `text` property and will throw an error. – RobG Feb 12 '13 at 08:34