jQuery selector eliminating zero incorrectly

Asked

Viewed 32 times

2

In the following case, you have a code being entered in the attribute data-produto of my input.

$(".valor.partida").bind('blur', function(){
  alert($(this).data("produto"));
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<input class="valor partida" type="text" name="novo_valor_partida-1" value="11,11" data-produto="0101000" data-id="1">

The problem is that when obtaining the value of this attribute, it returns without the initial zero, only 101000.

Why does this happen?

1 answer

5


Don’t trust the .data() jQuery, he’s not to be trusted :)

In this case the version 1.4 it intepretates this string as number(!), but this has been corrected in newer versions and already returns string.

Uses native Javascript:

$(".valor.partida").bind('blur', function(){
     alert(this.dataset.produto);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<input class="valor partida" type="text" name="novo_valor_partida-1" value="11,11" data-produto="0101000" data-id="1">

In a another answer referred to this problem, the @bfavaretto has also an excellent explanation on the internal processes of .data() jQuery.

  • This way it is working correctly but what would be the problem with the data? He does some conversion or black magic?

  • 2

    @Marcelodeandrade http://answall.com/questions/50349/jquery-n%C3%a3o-usa-o-dataset-do-Html5-no-data

  • +1 @bfavaretto for clarification

  • 1

    @Marcelodeandrade joined the answer. He treats as Number, that was however corrected in later versions.

  • 1

    I was just waiting for the team to accept your answer, @Sergio. It was enough to clear the doubts.

  • 1

    @bfavaretto this your answer is very good. Linkei. You can not double up :P

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.