Is there any HTML/JavaScript code that can allow the viewer of a webpage to add a option to a dropdown select list by typing it in a text box???
Asked
Active
Viewed 316 times
4
-
Yes, it's very simple to write such code if you know basic Javascript. – Barmar Jul 28 '15 at 18:34
-
Use document.createElement('option') to create an option element and add to your select – Ricardo Pontual Jul 28 '15 at 18:39
-
I've hardly ever written ANY JavaScript as I've only just fully learned HTML and JavaScript @Barmar – Adam Crookes Jul 28 '15 at 18:49
-
@RicardoPontual I've hardly ever done JavaScript so would you be able to tell me how to do the full code, and how it links to HTML?? – Adam Crookes Jul 28 '15 at 18:51
-
Do you want the solution to include jQuery or no? – Kwarrtz Jul 28 '15 at 18:53
-
@AdamCrookes SO is not a free code-writing service or a replacement for learning how to program. We're here to answer specific questions you have about the code you've written, not to do it for you. – Barmar Jul 28 '15 at 18:54
-
Just google it and you'll find a lot of examples Adam. Check this out, here there's a fiddle you can see html and javascript code: http://stackoverflow.com/questions/8674618/adding-options-to-select-with-javascript – Ricardo Pontual Jul 28 '15 at 18:57
1 Answers
3
Very basic example. No CSS, fancy formatting, error checking, anything. The value of the new option will be identical to the displayed string.
function newOpt() {
var $inp = $('#newOptIpt');
var v = $inp.val();
$('#modSelect').append('<option value="' + v + '">' + v + '</option>');
$inp.val('')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<select id="modSelect">
<option value="default-1">Default option</option>
</select>
<br><br>
<input id="newOptIpt"/>
<button onclick="newOpt();">Add Option</button>

Kwarrtz
- 2,693
- 15
- 24