简体   繁体   中英

Get value of multiple dropdown list and compare each dropdown using javascript

How can I compare 2 select option values using javascript?

Here's my code so far:

echo "  
    <div class='control-group'>

        <label class='control-label' for='focusedInput'>Color Combination $x</label>

        <div class='controls'>
            <select name='color1[]' class='form-control'  id='color1' onchange='getcolor()' required>
";


    $statement = $db->prepare("SELECT * FROM color order by colorName ASC");
    $statement->execute();



    while($rows = $statement->fetch(PDO::FETCH_ASSOC)) {

        echo "<option value='" .$rows['colorName']. "'>" . $rows['colorName'] . " - " . $rows['colorCode'] ."</option>";
    }
    echo "</select>";


echo "&nbsp; &nbsp; <select name='color2[]' class='form-control'  onchange='getcolor()' id='color2'><option value=''>N/A</option>";

    $statement = $db->prepare("SELECT * FROM color order by colorName ASC");
    $statement->execute();



    while($rows = $statement->fetch(PDO::FETCH_ASSOC)) {
        echo "<option value='" .$rows['colorName']. "'>" . $rows['colorName'] . " - " . $rows['colorCode'] ."</option>";
    }
    echo "</select>";

How can I compare color1 and color2 to determine if they are the same?

Here's the javascript that only validates the first column:

 function getcolor() {
            var colorcombination1=(document.getElementById("color1").value);
            var colorcombination2=(document.getElementById("color2").value);




     if (colorcombination1 == 'BLACK' && colorcombination2 == 'BLACK') {
                    alert("Same color");

                }

It only validates first column but I have 6 columns that I need to validate dynamically. Whenever I change the number of colors the number of dropdown lists will display.

I can't post the picture here because it requires 10 reputation and I'm new here.

Can you help me on how can I validate the other dropdown? Thanks!

  1. You don't have to repeat second query to database,
    if your second query is the same.
    $rows = $rows2; .

  2. if ( colorcombination1 == colorcombination2 ) { alert( "Same color" ); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM