Skip to content
Advertisement

CharAt not working within table and input within .each loop

The Goal: To get the first character in the input field and place it next to the input box. I’m trying to this for sorting purposes. jQuery datatables won’t work and I’m looking for an alternate solution.

Possible Solution: Get the first char charAt(0) and place it next to the input field to make that column ‘sortable’.

Desired Result:

  • D [Doom, Doctor]
  • S [Storm, Johnny]

When I removed the .each loop below it does work, so I’m wondering if it’s just a syntax issue?

I’ve tried ID’s and GetElementsByClassName, but only have luck with ID’s. But ID’s should only be used once, I was just trying to get it to work :/. Any suggestions?

$("input").each(function (index) {
  var x = document.getElementById("nameSort").value;
  var Val = x.charAt(0);
  document.getElementById("nameSort").insertAdjacentHTML("beforebegin", Val);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <tr><th>Name</th></tr>
  <tr>
    <td>
     <input id="nameSort" class="sortme" value="Doom, Doctor">
    </td>
  </tr>
  <tr>
    <td>
      <input id="nameSort" class="sortme" value="Storm, Johnny">
    </td>
  </tr>
</table>

Advertisement

Answer

You are reusing IDs. To fix this issue, just use the this keyword in jQuery. Just like this:

$("input").each(function (index) {
  var val = $(this).val().charAt(0);
  $(this).before(val + " ");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <tr><th>Name</th></tr>
  <tr>
    <td>
     <input id="nameSort" class="sortme" value="Doom, Doctor">
    </td>
  </tr>
  <tr>
    <td>
      <input id="nameSort" class="sortme" value="Storm, Johnny">
    </td>
  </tr>
</table>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement