javascript: form select option and input field


Solution 1

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()

Solution 2

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:

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

Related videos on Youtube

Author by


Updated on June 14, 2022


  • JasperM
    JasperM over 1 year

    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>
    <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?

  • David G
    David G about 11 years
    Even so, that won't fix that problem.
  • Logda
    Logda about 11 years
    Unless he meant something else, what he's asking for is the opposite, wanting to select the value based on the typed text, not get the value from the select list. Though his response to your comment suggests this is the correct answer. Oi.