Reputation: 914
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
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
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
Reputation: 31043
try
$('#ddlRoles').find("option[value='"+role+"']").attr("selected","selected");
Upvotes: 1