Igor Yakushchenko Igor Yakushchenko -4 years ago 90
Javascript Question

How to autoselect option depending on input's value

I need select's option to be actually selected on document ready depending on an input's value.

Example:

<select id="mySelect">
<option value="1">myVal1</option>
<option value="2">myVal2</option>
</select>

<input type="text" id="myId" value="2">


For example, we've got a predefined value '2' of the input on page load. I need select-box to be auto-selected with it's option having the same value as input 'myId'. I mean 'mayVal1' must be selected.

When input has no value select must behave as default.

Thanks!

Answer Source

Your mention of "on document ready" sort of suggests that you might be using jQuery, with that assumption made (albeit perhaps erroneously), I offer you this:

$(document).ready(
    function(){
        var theValue = $('#myId').val();
        $('option[value=' + theValue + ']')
            .attr('selected',true);
    });

With a demo at JS Fiddle.


Edited in response to OP's question:

How do I compare option's value to very first word in the input's value? I mean if I have option value 'hello' and input value 'hello world' script have to select option containing 'hello' in its value.

Right, given the disparity between your posted example and your question, I'm going to try to address both of the possibilities.

First, to select an option based on its text component (in your above code, the 'myVal1','myVal2' bits):

$(document).ready(
    function() {
        $('form:eq(0)').submit(
            function() {
                var theValue = $('#myId').val().split(" ",1);
                $('option:contains(' + theValue + ')').attr('selected', true);
                return false;
            });
    });

JS Fiddle demo: note that the text component of the option element does not represent the value of the option element.

Secondly, if you want to link the first part of the value entered into the myId input element to the value of the select/option element(s):

$(document).ready(
    function() {
        $('form:eq(0)').submit(
            function() {
                var theValue = $('#myId').val().split(" ",1);
                $('option[value=' + theValue + ']').attr('selected', true);
                return false;
            });
    });

JS Fiddle demo.

These demos could work with keyup(), or equivalent actions/events, but submit() seemed the better choice.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download