Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change "selected" value in combobox using JavaScript?

I have 2 comboboxes, "combo1" and "combo2",

If I select any value in combo1, I need that same value in combo2 as "selected" by JavaScript. What JavaScript code should be added to the HTML below to make it work?

<html>
    <head>
        <title>combo</title>
    </head>

    <body>
        <form name="testForm" action="" method="post">
            <select name="combo1">
                <option value="1">option 1</option>
                <option value="2">option 2</option>
                <option value="3">option 3</option>
            </select><br /><br />
            <select name="combo2">
                <option value="1">option 1</option>
                <option value="2">option 2</option>
                <option value="3">option 3</option>
            </select>
        </form>
    </body>
</html>
like image 212
Alex Avatar asked Dec 14 '22 01:12

Alex


2 Answers

<script type='text/javascript'>
    window.onload = function() { BindEvent(); }

    function BindEvent()
    {
        var elemToBind = document.getElementById ( "cmb1" );
        elemToBind.onchange = function () { SetSel ( this ); }
    }
    function SetSel(elem)
    {
        var secondCombo = document.getElementById ( "cmb2" );
        secondCombo.value = elem.value;   
    }
</script>
<body>
    <select id="cmb1">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
    <select id="cmb2">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
</body>
like image 88
rahul Avatar answered Mar 07 '23 02:03

rahul


onChange() can help <select name="combo1" onChange="changeCombo2(...)">

like image 39
Niklas Rosencrantz Avatar answered Mar 07 '23 01:03

Niklas Rosencrantz