Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Using javascript, (no jQuery libraries)

What i'd like to do is when I type a value into the inputbox and I hit my enter key (in the textbox only) i'd like to have the value of the inputbox be added into the drop down box.

Note that if there is an existing value in the already in the drop down box, the next value should just be added below the existing value.

How do I set this up?

Here is the html setup:

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<input type="text" id="theinput" style="width: 100px;">

<select id="thebox" style="width: 100px;"></select>

</body>

</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
151 views
Welcome To Ask or Share your Answers For Others

1 Answer

First - lets add an event listener, that will be fired when user press a key

Second - Let's make a function passing the element you want to get the user input and set the value in the document

Third - let's create the dom element and add it to the out element you've created:

<script>
    //your input element
    var in = document.getElementById("theinput");
    //step 2
    function addItem(e) {
      //check if user press Enter
        if (e.keycode == 13) {            
            var out = document.getElementById("thebox");

            //step 3
            var optionElement = document.createElement("option"); //will create al <option> tag
            var text = document.createTextNode(in .value); //the value you inserted
            optionElement.appendChild(optionElement); // add the text to <option>
            out.appendChild(optionElement); // add the option to <select>
        }
    }
//Step 1 - add Eventlistener
  in.addEventListener("keydown", addItem, false);
</script>

Obs.: dont tested it. Make the necessary adjustments.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...