3
votes

I have an form input field, when a user types "text 2", I want that "text 2" selected in the form select:

<select id="formsel">
    <option value="text 1">text 1</option>
    <option value="text 3">text 2</option>
    <option value="text 3">text 3</option>
</select>
<input type='text' id='input' />

I get the value from the input like this:

var input_val = document.getElementById('input').value; 

But I can not select the option from the dynamic form select with

document.form.formsel.value = input_val;

Can anyone see what I'm doing wrong?

4
jQuery has warped me - all I can think of is $("#formsel option:selected").text() - Adam Rackis
cool - posted as answer in that case. - Adam Rackis

4 Answers

3
votes

Your code doesn't show the form you are trying to access with document.form, so I'm assuming there is no form. Try accessing the select by its id. This seems to work for me:

<script>
document.getElementById('input').onkeyup = function()
{
    var input_val = document.getElementById('input').value;
    document.getElementById('formsel').value = input_val;
}
</script>
1
votes

Based on your comment, it looks like you're using jQuery (you should tag all questions with jQuery if that's the case).

This should get you what you want

var selectedText = $("#formsel option:selected").text()
0
votes

It looks like you might have a typo.

<option value="text 3">text 2</option>

Should be:

<option value="text 2">text 2</option>
0
votes

Try this:

var nodes = document.getElementById('formsel'),
    txt = document.getElementById('input').value, node;

for ( var i = nodes.length; i--; ) {

    node = nodes[i];

    if ( txt === nodes[i].value ) {

        node.selected = true; break;

    }

}