I have a problem when trying to set selected option from javascript.
I created one select and added options with php from mysql like this:
<select class="form-control input-group-lg" name="progress" id="progress">
<?php
if ($conn === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM progress";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$progress_name = $row['name'];
echo "<option>$progress_name</option>";
}
}
else {
echo "<option>Fault!</option>";
}
}
else {
echo "$sql. " . mysqli_error($conn);
}
mysqli_close($conn);
?>
</select>
And then set selected option from javascript like this:
$('#progress').val("Value to set");
This method works fine and it sets selected option with that value which I want.
ANOTHER METHOD:
I have php file and I select data from database (MySQL) in json and then using ajax like this
$.ajax({
url: 'data_control/orders/progress_select.php',
type: 'get',
method: "POST",
data: {selected_value:selected_value},
dataType: 'JSON',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var progress_name = response[i].progress_name;
var option = document.createElement("option");
option.text = progress_name;
option.value = progress_name;
var select = document.getElementById('progress');
select.appendChild(option);
}
}
});
Options are added successfully, but I can’t set selected value in this way:
$('#progress').val("Value to set");
Thanks for help!