HenryDev HenryDev - 5 months ago 9
Javascript Question

How to remove the first charcter of nnumber in jquery?

I'm trying to remove the first charcter of my numbers, but I'm not sure why it's not working. After executing my code I want to have these numbers:

3032659875

3032369875

5456663323

3265333333

3032659898

Any help please?? Thanks a lot!

Here's my code:

<table>
<tr>
<td class = "usersPhoneNumber">13032659875</td>
</tr>
<tr>
<td class = "usersPhoneNumber">13032369875</td>
</tr>
<tr>
<td class = "usersPhoneNumber">15456663323</td>
</tr>
<tr>
<td class = "usersPhoneNumber">13265333333</td>
</tr>
<tr>
<td class = "usersPhoneNumber">13032659898</td>
</tr>
</table>


JQuery

$(document).ready(function (){
var theNumber = $(".usersPhoneNumber");
if ((theNumber.text()).length === 11) {
var val = $(this).html();
$(this).html(val.substring(1, val.length));
}
});


Live Demo
https://jsfiddle.net/henrygranados/mLar8bja/

Answer

It doesn't work because .usersPhoneNumber are multiple elements so you need to loop trough them:

$(document).ready(function() {
  // loop over your elements
  $(".usersPhoneNumber").each(function() {
    // check if elements length is 11
    if ($(this).text().length === 11) {
      var val = $(this).html();
      $(this).html(val.substring(1, val.length));
      console.log("tes33");
      alert("testing");
    }
  })
});

Updated Fiddle

Comments