MDB MDB - 2 months ago 7
HTML Question

Set/show the selected/saved value(from database) to a select box for editing purposes

I'm trying to get the value I have saved to database and show it in a select box.
The items in the select box is populated from the database.

<select id="sel2" name="sel2">
<option value="">---</option>
<?php
require("connection.php");

$res = mysqli_query($conn, "SELECT field FROM table");
while($row = $res->fetch_assoc()){
echo "<option value='".$row['field']."'>'".$row['field']."'</option>";
}
?>
</select>


Now, when I try to do this,

$('#btn2').click(function(){
var x = "field1";
$('#sel2').val(x);
});


the value of x do not appear in the select box. But when the items are not fetch from the database like,

<select id="sel2" name="sel2">
<option value="">---</option>
<option value="field1">field1</option>
<option value="field2">field2</option>
<option value="field3">field3</option>
</select>


the jquery works.

I don't know what I am missing here. Could you help me on this. How to set the selected value(came from database that was chosen before) of a Select box when the items were populated from the database?

I am fetching the items of select box from the database because there are too many of them. Please help.

Answer

The problem is that the jquery code is being executed right BEFORE the fields are fetched from the database. Thus the statement $('#sel2').val(x); can't set the value x because at that time, the x field doesn't exist in the select dropdown.

If unsure, try to use a timeout in the jquery click function just to check if whatever I have said is true or not.

Let me know if it worked.

Comments