jquery: trying to set a select option -


i have form select dynamically populate:

<div id="addrecordform">     <h2 class='uiblocktitle'>add record</h2>     <p class="forminstructions">all entries 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 department</option>";                  <?php                      $query = "select * departments";                     $results = $db->getresults($query);                      while($row = mysql_fetch_array($results)){                         if (count($results) > 0) {                              //get department , id                             $department = $row['department'];                             $deptid = $row['id'];                              print "<option value=\"" . $deptid . "\">" . $department . "</option>";                          }                     }                 ?>              </select></p> 

i trying set selected option based on 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 being returned correctly , corresponds 1 of values in drop down, both being pulled same field of same database table, spelling isn't issue. reason cannot select selected correct option. i've tried hard coding values in no luck. i've tried variations of $("#departments").val(), using option index, etc., nada. doing wrong? thanks.

if option value (not index, not text), 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 change handler, in case that's you're running trouble with:

$("#theselect")   .change(function() {     $("<p>changed!</p>").appendto(document.body);   })   .val("val4")   .change(); 

live copy


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -