Reputation: 177
I have a dropdown list that is populated from a mySQL database using PHP. How do I preselect the first option in the dropdown bearing in mind that these values may not always be the same?
This is the code in my HTML:
function loadparameters(selobj, url, nameattr) {
$(selobj).empty();
$.getJSON(url, {}, function (data) {
$.each(data, function (i, obj) {
$(selobj).append($("</option><option>
</option>").val(obj[nameattr]).html(obj[nameattr]));
});
});
}
$(function () {
loadparameters($('select#parameterType').get(0),
'GetParameter.php?GetParameter=parameterType', 'parameterType');});
..and the PHP Script:
<?php
if(!empty($_GET['GetParameter']))
{
$list = $_GET['GetParameter'];
$qry='';
switch($list)
{
case 'parameterType':
{
$qry = "SELECT parameterType FROM Parameters";
break;
}
}
if(empty($qry)){ echo "invalid params! "; exit; }
$dbconn = mysql_connect('*******','*******','******')
or die("DB login failed!");
mysql_select_db('*****', $dbconn)
or die("Database does not exist! ".mysql_error($dbconn));
$result = mysql_query($qry,$dbconn)
or die("Query $qry failed! ".mysql_error($dbconn));
$rows = array();
while($rec = mysql_fetch_assoc($result))
{
$rows[] = $rec;
}
mysql_free_result($result);
mysql_close($dbconn);
echo json_encode($rows);
}
?>
Upvotes: 0
Views: 313
Reputation: 6256
The only thing that seems wrong in your code is this line
$(selobj).append($("</option><option></option>").val(obj[nameattr]).html(obj[nameattr]));
Why do you close close/open/close the option tag?
Shouldn't it be that way? (I've indented the code for readability)
$(selobj).append(
$("<option></option>") // only open/close tag
.html(obj[nameattr]) // this injects HTML
);
OR
$(selobj).append(
$("<option></option>") // only open/close tag
.text(obj[nameattr]) // this only injects text
);
If you fix this, then the first option should be preselected. The reason why it isn't preselected is because your browser might automatically fix this issue by itself with an empty option.
Also, I find the syntax below more readable:
var option = $("<option></option>").text(obj['nameattr']);
$(selobj).append(option);
Upvotes: 2