Click here to Skip to main content
15,908,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Friends,

Need a help ..
I have a dropdown with few values like below

Gender
XML
<select class="form-control" tabindex="6" id="ddlSex">
   <option value="M">Female</option>
   <option value="N">Male</option>
</select>

service returning the Gender as "N" but there is no id assosicated with it
how to assign based on Gender="N" through jquery tried something like this
JavaScript
$.each(item.Sex, function (i,item1) {
      if (i == 'N') {
          $("#ddlSex").val(item1.Sex).trigger('change');
      }
  });

but it is throwing runtime error message .. can someone help me how to do it
Posted
Updated 6-Jan-16 3:40am
v2
Comments
ZurdoDev 6-Jan-16 9:47am    
Looking at your options, isn't "N" for Male? So, what exactly is your question?
Member 12137386 6-Jan-16 10:01am    
ya .. If "N" then dropdown should change to Male

1 solution

Use below code in place of $("#ddlSex").val(item1.Sex).trigger('change');
JavaScript
$("#ddlSex option[value='"+item1.Sex+"']").attr("selected", true)
 
Share this answer
 
v2
Comments
Member 12137386 6-Jan-16 10:21am    
Thanks for the quick response .. I replaced and tried but it is thorwing a runtime exception
0x800a138f - JavaScript runtime error: Invalid operand to 'in': Object expected

Code:

$.each(item.Sex, function (i,item1) {
if (i == 'N') {
$("#ddlSex option[value='"+item1.Sex+"']").attr("selected", true)
}
});
Murali Gowda 6-Jan-16 10:58am    
I'm assuming the item object will look like below,

Code:
var item = [];
item.Sex = ['N', 'M'];
$.each(item.Sex, function (i, item1) {
if (item1 == 'N') {
$("#ddlSex option[value='" + item1 + "']").attr("selected", true)
}
});


hope this works for you.
Member 12137386 6-Jan-16 11:13am    
no still the same error message .. service returing few other values also Gender is one in that response looks like this

Age 3
Altered false
HuntingNumber null
Name James
Sex "N"
Murali Gowda 7-Jan-16 1:26am    
What is your object structure?
Is it like,
item=[{Age:3,Altered:false,HintingNumber:null,Sex:"N"},
{Age:5,Altered:false,HintingNumber:null,Sex:"M"}]

If so, then loop on item not on item.Sex

ex: $.each(item,function(I,item1){
if(item1.Sex=='N'){
$("#ddlSex option[value='" + item1 + "']").attr("selected", true);
}
});
Member 12137386 7-Jan-16 10:29am    
Thanks for the solution it worked :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900