Elisabeth
Elisabeth

Reputation: 21226

8 ist not "8" in a javascript comparison

I have a hidden field with value "8" and I return json data from my asp.net mvc controller where the templateId has a value of 8.

"8" is not 8. Thats fine but how can I compare then both values?

enter image description here

Upvotes: 0

Views: 167

Answers (5)

Elisabeth
Elisabeth

Reputation: 21226

Instead of writing:

if( response.templateId == $('#TemplateId').val())
{
    // never hit here
}

I did this and it worked:

var selectedTemplateId = $('#TemplateId').val();
if (response.templateId == selectedTemplateId)
{
   // it works
}

I also did a general test: 8 is the same as "8":

if( 8 == "8")
{
    // always hit here
}

Upvotes: 0

Anoop
Anoop

Reputation: 23208

In JavaScript you can compare two variable with type check or without type check

eg

 8 == '8' //true /* dont check type*/
 8=== '8'   //false /* check type*/

You don't need type checking while comparing. so your code will work fine.

Since you saying that your code is not working. and value of $("#TemplateId").text() is '8'( shown in console). only possible problem is response.templateId is not equals to 8.

Upvotes: 3

user3266190
user3266190

Reputation:

You can always parse "8" to an Integer with "parseInt(str, 10)"

Upvotes: 1

Sean3z
Sean3z

Reputation: 3745

Have you tried parseInt($('#TemplateId').text())?

Upvotes: 3

Marten
Marten

Reputation: 1356

You could apply parseInt() to the string returned from text().

Upvotes: 2

Related Questions