3

I have a razor view with:

<select id="roletypeddl" >
   <option value="@roletype.Id" selected="selected" data-assignabletoperson="@roletype.AssignableToPerson" >@roletype.Name</option>
</select>

So in jquery I wanted to run some code if data-assignabletoperson was true hence:

if ($('#roletypeddl').find('option:selected').data('assignabletoperson') == true)
{
  do something
}

Trouble is this code is never getting executed.

I figure it has to do with the html being produced being:

<select id="roletypeddl">
  <option data-assignabletoperson="True" selected="selected" value="5">Manufacturer</option>
</select>

I think the problem is that the "True" is capitalised. Anyone know how to get around this?

user2005657
  • 607
  • 10
  • 20

2 Answers2

2

data- attribute does not know your data type. @roletype.AssignableToPerson html output is True, but this is not bool value, this is string...

following statement

data-assignabletoperson="True"

is not bool value, its string, So you should compare like this:

if ($('#roletypeddl').find('option:selected').data('assignabletoperson') == "True")
{
    do something
}

Update: data knows your data type. Problem is the "True". It must be "true".

And the EXAMPLE

AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197
  • Thanks, makes sense and works. Strange because the correct answer at http://stackoverflow.com/questions/9921076/retrieve-boolean-data-from-data-attribute-in-jquery seems to disagree with this and says data() can handle boolean data? – user2005657 Mar 21 '13 at 08:20
  • Yes. I saw it, you right. Answer is your suggestion `I think the problem is that the "True" is capitalised` – AliRıza Adıyahşi Mar 21 '13 at 08:22
0

Try using:

data-assignabletoperson="@roletype.AssignableToPerson.ToLower()"

Eg.

<select id="roletypeddl" >
   <option value="@roletype.Id" selected="selected" data-assignabletoperson="@roletype.AssignableToPerson.ToLower()" >@roletype.Name</option>
</select>

Refer:

Why does Boolean.ToString output “True” and not “true”

Also, You can use javascript:

.toLowerCase()

Eg.:

if ($('#roletypeddl').find('option:selected').data('assignabletoperson').toLowerCase() == 'true')
{
  //do something
}
Community
  • 1
  • 1
Kapil Khandelwal
  • 15,958
  • 2
  • 45
  • 52