Home > Mobile >  CharAt not working within table and input within .each loop
CharAt not working within table and input within .each loop

Time:09-28

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?

<table >
  <tr><th>Name</th></tr>
  <tr>
    <td>
     <input id="nameSort"  value="Doom, Doctor">
    </td>
  </tr>
  <tr>
    <td>
      <input id="nameSort"  value="Storm, Johnny">
    </td>
  </tr>
</table>

$( "input" ).each(function( index ) {
  var x = document.getElementById("nameSort").value;
  var Val = x.charAt(0);
document.getElementById("nameSort").insertAdjacentHTML("beforebegin", Val);
});

CodePudding user response:

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 >
      <tr>
        <th>Name</th>
      </tr>
      <tr>
        <td>
          <input id="nameSort1"  value="Doom, Doctor" />
        </td>
      </tr>
      <tr>
        <td>
          <input id="nameSort2"  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>

CodePudding user response:

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 >
  <tr><th>Name</th></tr>
  <tr>
    <td>
     <input id="nameSort"  value="Doom, Doctor">
    </td>
  </tr>
  <tr>
    <td>
      <input id="nameSort"  value="Storm, Johnny">
    </td>
  </tr>
</table>

  • Related