最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to autoselect option depending on input's value - Stack Overflow

programmeradmin3浏览0评论

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!

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!

Share Improve this question edited Sep 7, 2022 at 14:12 dan1st 16.4k17 gold badges95 silver badges129 bronze badges asked Dec 4, 2010 at 16:12 Igor YakushchenkoIgor Yakushchenko 831 gold badge1 silver badge7 bronze badges 6
  • Are you using any javascript framework? Or you're looking at how to do this using plain javascript – Andreas Wong Commented Dec 4, 2010 at 16:21
  • Sorry I forgot to say that I'm using jquery – Igor Yakushchenko Commented Dec 4, 2010 at 16:36
  • @AndreasWong, please edit the title and possibly the post itself to add whether you'd prefer or allow answers that use jQuery. The tag is a good place to start but it's good to be clear for others searching for similar solutions. – jpierson Commented Feb 9, 2022 at 19:21
  • What exactly is meant by "select must behave as default" do you mean it should behave as it would given the above markup and without the value being set deliberately? – jpierson Commented Feb 9, 2022 at 19:22
  • It's not even my question o_O @jpierson – Andreas Wong Commented Jul 1, 2022 at 8:30
 |  Show 1 more ment

4 Answers 4

Reset to default 6

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 pare 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 ponent (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 ponent 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.

something like below should work///

<select>
    <option value="0">One</option>
    <option value="1">Two</option>
</select>

$(document).ready(
    var inputValue = $('#id').val();
    $('select').val('1'); // selects "Two"
    $('select').val(inputValue); // also selects "Two"

});

in vanilla JS:

var listener = function(ev){
var input = document.getElementById('myId');
for(var i = 0, elems = document.getElementById('mySelect'), l = elems.length; i < l; i++)
    elems[i].selected = elems[i].value == input.value;    
}
listener();
document.getElementById('myId').addEventListener('change', listener, false);

with jQuery:

$(function(){
    $('#myId').change(function(){
       $('#mySelect option').removeAttr('selected').filter('[value=' + $(this).val() + ']').attr('selected', true);
    }).change()
})

$('#mySelect').val('2').change();

发布评论

评论列表(0)

  1. 暂无评论