L. Grunn L. Grunn - 6 months ago 12
jQuery Question

How to change the name, but not the value of a dynamically filled select list?

I have a select list that is dynamically filled with data from my database. But I don't want the users to see the real column names, so I created a extra column in my database called column_alias. What I want, is to show the column_alias names in the dropdown but keep the real values of column names.

This is my .html file:

<div class="select_table col-md-6">
<label for="invoerTabelNaam">Select table:</label>
<span>
<select class="form-control" name="table_names" id="slctTable">
</select>
</span>
</div>


This is how I'm filling the select list with the real column names at the moment:

function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}

$("#slctTable").append(optionsTables);
$("#slctTable").change();
});

}


And this is the code that get's the data outof my database:

<?PHP

require "opendb.php";

$query = "select table_name
from db_tables
order by table_name";

$data = pg_query($conn, $query);

$table_names = array();

while ($row = pg_fetch_array($data))
{
array_push($table_names, $row["table_name"]);
}

echo json_encode($table_names);

require "closedb.php";
?>


Update

This is what my database table looks like:
enter image description here

So I want the table_alias to be visible in my select list, but I want the value to be table_name so it can interact with my database.

Answer

Firstly you will need to fetch the alias as well from the database.Change your server side code to the following.

<?PHP

require "opendb.php";

$query =    "select table_name,table_alias 
            from db_tables 
            order by table_name";

$data = pg_query($conn, $query);
$table_names = array();

while ($row = pg_fetch_array($data))
{
    array_push($table_names, $row);
}
echo json_encode($table_names);
require "closedb.php";
?>

Then in your client side code simply output the table_alias as option name and table_name as option value.

function loadTables() {
    $.getJSON("dropdown_code/get_tables.php", success = function(data)
    {
        console.log('inside callback');
        var optionsTables = "";
        for(var i = 0; i < data.length; i++)
            {
                optionsTables += "<option value='" + data[i]['table_name'] + "'>" + data[i]['table_alias'] + "</option>";
            }

    $("#slctTable").append(optionsTables);
    $("#slctTable").change();
}); 
}
Comments