skip to Main Content

How can I select all HTML items by name ending with a name using jQuery

<input type="text" name="[0].LastName" value="Smith">
<input type="text" name="[1].LastName" value="James">
<input type="text" name="[2].LastName" value="Wilson">
<input type="text" name="[3].LastName" value="Peterson">

For instance if I wanted in jQuery loop through the multiple elements but only select Element Names ending with ].LastName, therefore it should only return the 3 elements above.

3

Answers


  1. You can use [attr$=value] to select elements whose attr attribute ends with value.

    $('input[name$="Name"]').each((i, el) => console.log(el));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" name="[0].LastName" value="Smith">
    <input type="text" name="[1].LastName" value="James">
    <input type="text" name="[2].LastName" value="Wilson">
    <input type="text" name="[3].LastName" value="Peterson">
    Login or Signup to reply.
  2. You can use the ends with selector:
    https://api.jquery.com/attribute-ends-with-selector/
    e.g:

    $("[name$='.LastName']")
    
    Login or Signup to reply.
  3. See comment in the code below. But also, you could just name all of those elements the same name and then when the form submits, the data will be combined into a comma delimited string.

    // Just pass a valid CSS Selector to JQuery:
    let elements = $("input[name$='LastName']");
    
    console.log(elements);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" name="[0].LastName" value="Smith">
    <input type="text" name="[1].LastName" value="James">
    <input type="text" name="[2].LastName" value="Wilson">
    <input type="text" name="[3].LastName" value="Peterson">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search