Reputation: 45
I have two dropdowns where the options are coming from an API dynamically. I am trying to select the option dynamically using jquery. The first dropdown gets selected but the second do not.
I am trying to achieve this using $('#id').find(option [value = ""]).attr(selected, selected);
These are the HTML fields..
<div class="form-group">
<label>Branch</label>
<select class="form-control" id="ddlSelectBranch" data-val="true">
</select>
</div>
<div class="form-group">
<label>User Role</label>
<select class="form-control" id="ddlSelectRole" data-val="true">
</select>
</div>
This the Jquery Code..
$('#ddlSelectBranch').find("option[value='" + item.branchDTO.branchId + "']").attr('selected', 'selected');
$('#ddlSelectRole').find("option[value='" + item.roleDTO.roleId + "']").attr('selected', 'selected');
This is the object I'm currently working on..
branchDTO: {branchId: 6, branchName: "Bandhan Serampore"}
loginId: "BK1234"
roleDTO: {roleId: 1, roleName: "program datector"}
userEmailPrimary: "[email protected]"
userEmailSecondary: ""
userFirstname: "Pragyan"
userId: 25
userLastname: "Ojha"
userMiddlename: "Ganesh"
userMobilePrimary: "9635200456"
userMobileSecondary: "7896523647"
The branch field gets selected but it's not working on the role field.
Upvotes: 0
Views: 488
Reputation: 780889
Instead of setting the selected
option, just set the value of the dropdown:
$("#ddlSelectBranch").val(item.branchDTO.branchId);
$("#ddlSelectRole").val(item.roleDTO.roleId);
However, your method should work as well. If it's not working, the problem must be that item.roleDTO.roleId
doesn't actually match the values of any of the options. Make sure there's no extra whitespace in the option values.
Upvotes: 1