I have a form select that I dynamically populate:
<div id="addRecordForm">
<h2 class='uiblocktitle'>Add Record</h2>
<p class="forminstructions">All entries are required</p>
<form id="userform">
<p class="label">Date:</p><p><?php print $_SESSION['longdateform']; ?></p>
<p class="label"><label for="departments" class="bodylabel">Department:</label></p>
<p>
<select id="departments" name="departments">
<option value="null">Select A Department</option>";
<?php
$query = "SELECT * FROM departments";
$results = $db->getResults($query);
while($row = mysql_fetch_array($results)){
if (count($results) > 0) {
//get department and id
$department = $row['dep开发者_JS百科artment'];
$deptID = $row['id'];
print "<option value=\"" . $deptID . "\">" . $department . "</option>";
}
}
?>
</select></p>
I then am trying to set the selected option based on some user data.
//get user department
$.ajax({
type: "POST",
url: "lib/includes/getUserDepartment.php",
data: "empname=" + empname,
success: function(data){
$("#addRecordForm").slideDown('fast');
$('#departments').val(data).change();
}
});
the var data is being returned correctly and corresponds with one of the values in the drop down, they are both being pulled from the same field of the same database table, so spelling isn't an issue. For some reason I cannot get the select selected to the correct option. I've even tried hard coding the values in with no luck. I've tried variations of $("#departments").val(), using the option index, etc., nada. What am I doing wrong? Thanks.
If you do it with the option value
(not its index, not its text), it should work. Example:
HTML:
<select id='theSelect'>
<option value='val1'>Item 1</option>
<option value='val2'>Item 2</option>
<option value='val3'>Item 31</option>
<option value='val4'>Item 4</option>
<option value='val5'>Item 5</option>
</select>
JavaScript:
$("#theSelect").val("val4");
Live copy
Or with the change
handler, in case that's what you're running into trouble with:
$("#theSelect")
.change(function() {
$("<p>Changed!</p>").appendTo(document.body);
})
.val("val4")
.change();
Live copy
You must use the department ID ($row['id']
in your PHP code example) to set the chosen option in your select, since that's what you set for the option value
attribute.
$('#departments').val('null');
would select the "Select A Department" option, for example. I've created a jsfiddle example for you that illustrates this.
There is also a stray ";
in your example, right after the closing </option>
tag of your "Select A Department" null option.
You did not share the code for getUserDepartment.php in your example, so I cannot verify if that method is indeed returning the row id and not the row department
column.
精彩评论