0

I want to get the selected SystemID from my drop down menu which is populated by a database. I have named the drop down"data3"

Drop down from database is all working, it is displaying all the SystemIDs from my table.

Code below:

<select id ="data3" style="position:relative; top:-70px; left: 3.6%;" 
name="data3" class="btn btn-light btn-sm dropdown-toggle">
    <option value="SystemID">SystemID</option>
    <?php
        $sql = "SELECT DISTINCT SystemID FROM MyTable ORDER BY 
        SystemID";
    $result = sqlsrv_query($conn, $sql);
    while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
        echo "<option value=\"\">" . $row['SystemID'] . "</option>";
        }
    ?>
  </select>

How do I get the selected value from that drop down? I have tried doing

var data3=$("#data3").val();

But this returns nothing

Danny
  • 135
  • 8

1 Answers1

0

Use the ternary operator to check if the value coming from the database match the one from the select and mark it as selected. Please note that you must have a list of all the values of the select/option statement to be able to compare.

$row['SystemID'] == $value?'selected':''

echo "<option value='".$row['SystemID'] ."' ". ($row['SystemID'] == $value?'selected':'') ."  >" . 
        $row['SystemID'] . 
     "</option>";
Vidal
  • 2,605
  • 2
  • 16
  • 32
  • Also, when using a ternary operator when you concatenate strings, you usually need to group it with parentheses. `string ' . ($condition ? 'on true' : 'on false') . ' string`. Otherwise, PHP won't know when the `on false` results ends and the rest begins. – M. Eriksson Mar 04 '19 at 12:39
  • is not fully necessary but added the change for easy reading and identifying the ternary operator. thanks – Vidal Mar 04 '19 at 12:43
  • _"is not fully necessary"_ - As mentioned in my previous comment, in this context those parentheses are _very_ necessary, or the output will simply be wrong. [Here's a demo](https://3v4l.org/cKYb4) – M. Eriksson Mar 04 '19 at 12:48
  • you are correct, I use them in Laravel a lot inside {{}} and they are change to – Vidal Mar 04 '19 at 12:50