Accessing an array of HTML input text boxes using jQuery or plain Javascript

前端 未结 2 708
清酒与你
清酒与你 2021-01-12 07:50

I\'m looking to create a form which contains a dynamic number of input text boxes. I would like each text box to form part of an array (this would in theory make it easier f

相关标签:
2条回答
  • 2021-01-12 08:26

    First of all, id attribute cannot contains [ or ] character.

    There is lots of ways to get jQuery/plain JavaScript references to these elements. You can use descendant selector:

    <fieldset id="list-of-fields">
       <!-- your inputs here -->
    </fieldset>
    
    $("#list-of-fields input");
    document.getElementById("list....").getElementsByTagName("input");
    

    You can also use attribute selector:

    $("input[name^=field]");
    

    I'm not sure whether that's the only way but I think in plain JavaScript you'll have to fetch all input elements (document.getElementsByTagName) and then loop through array of these elements and check each element (whether it has name attribute which value starts with field).

    0 讨论(0)
  • 2021-01-12 08:29

    Give each element a class and access the group using jQuery:

    <p>Field 1: <input type="text" name="field[1]" class="fields"></p> 
    <p>Field 2: <input type="text" name="field[2]" class="fields"></p>
    <!-- etc... -->
    

    jQuery:

    $("input.fields").each(function (index)
    {
        // Your code here
    });
    

    This will run the anonymous function on each input element with a classname of "fields", with the this keyword pointing to the current element. See http://api.jquery.com/each/ for more info.

    0 讨论(0)
提交回复
热议问题