开发者

add text from textfield into selectbox at javascript? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for boo开发者_如何学JAVAks, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 8 years ago.

Improve this question

Can anyone point at good tutorial about adding text (by user) from textfield into select list (after clicking a button) with javascript?

thanks


Here is a simple jsfiddle that shows how you can dynamically add option to a select tag using JavaScript with input from a textfield:

HTML:

<select id='myselect'></select>
<input type='text' value='' name='mytext' id='mytext' />
<button value='submit' id='mybtn' name='submit'>submit</button>

JavaScript:

var myselect = document.getElementById('myselect');

function createOption(){
    var currentText = document.getElementById('mytext').value;
    var objOption = document.createElement("option");
    objOption.text = currentText ;
    objOption.value = currentText ;

    //myselect.add(objOption);
    myselect.options.add(objOption);
}

document.getElementById('mybtn').onclick = createOption;

Basically you have a text field, a button and a select box in the HTML. The submit button is attached with an onclick event that calls createOption function. The createOption function basically creates an option element and add it into the select box with option text and value equal to the text from the text field. Using document.getElementsById we are able to inject newly created element into the Selectbox and retrive the inserted value from the textfield.

However, if you are looking for a written tutorial this is a good reference to using JavaScript to dynamically populate a form Creating a Form Dynamically

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜