Sophonias
Sophonias

Reputation: 914

Iterate through select options

I am new to jquery and have been experimenting with it for the last couple of days and have been successful with it until I got to this point. I am working on an edit users page and I have problem choosing the right role from a list that is already populated from the datbase. //this is the select user drop down

  <select id="ddlUsers" name="ddlUsers" >
    <option value="0">--Select User--</option>
    <%for(Usertable user:usertableModel.getAllUsertables()){ %>
      <option id="<%=user.getUserid() %>" value="<%=user.getUserid() %>" 
          onclick= "showUserRole('<%=user.getRole().getRoleid() %>' )">     <%=user.getLastname() %> , <%=user.getFirstname() %>
   </option>
   <%} %>

// this is the select option for which I want to select the right role of the user selected from the first drop down.

<select name="ddlRoles">
  <%for(Role r:roleModel.getAllRoles()){ %>
    <option value="<%=r.getRoleid() %>"><%=r.getRolename() %></option>
  <%} %>
</select> 

//here is the jquery I tried to use

function showUserRole(role){
   $('#ddlRoles').each(function(){
      if($('option', this).val() == role){
    $('option', this).attr("selected","selected");
      }
  });
 }

but obviously its not working.... so any help is appreciated... thank you

Upvotes: 0

Views: 337

Answers (3)

dku.rajkumar
dku.rajkumar

Reputation: 18588

ddlRoles is the value of name attribute you cant use it as id selector. try this

if <select name="ddlRoles">

then

function showuserRole(role){
    $('select[name="ddlRoles"]').val(role);
}

else change it as <select id="ddlRoles">

then

function showuserRole(role){
    $('select#ddlRoles').val(role);
}

Upvotes: 1

AndrewR
AndrewR

Reputation: 6758

You can simplify your showuserRole function by just settings the value of #ddlRoles to the role you are passing in.

function showuserRole(role){
    $('#ddlRoles').val(role);
}

Upvotes: 0

Rafay
Rafay

Reputation: 31043

try

$('#ddlRoles').find("option[value='"+role+"']").attr("selected","selected");

Upvotes: 1

Related Questions