CharAt not working within table and input within .each loop

38 Views Asked by At

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>

2

There are 2 best solutions below

0
Michael M. On BEST 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>

0
user3252327 On

I think the main issue in your code is that id should be unique. You shouldn't use nameSort for both inputs.

A solution to your problem is to loop over $("input") and within the callback function, you can use this which will be the element you are looping on:

   <table class="table">
      <tr>
        <th>Name</th>
      </tr>
      <tr>
        <td>
          <input id="nameSort1" class="sortme" value="Doom, Doctor" />
        </td>
      </tr>
      <tr>
        <td>
          <input id="nameSort2" class="sortme" value="Storm, Johnny" />
        </td>
      </tr>
    </table>
    <script>
      $("input").each(function (index) {
        var x = this.value;
        var Val = x.charAt(0);
        this.insertAdjacentHTML("beforebegin", Val);
      });
    </script>