JQuery PHP Input Array of Input

I have a structure like this:

<input type='text' name='value[$x]' class='kp'> <input type='text' name='value[$y]' class='kp'> 

JQuery

 $( ".kp" ).keyup(function() { $('input[name^="value"]').each(function() { ***** HERE I WANT TO PRINT THE $x/$y VALUE INSIDE [] ***** }); }); 

Like my code, I want to get the variable $ x / $ y from an array. (with function .val (); I get a string inside the text box)

Is there any way? Thanks!

+5
source share
2 answers

You can use $(this) inside each to access the current element and use regex in the name attribute to retrieve the value.

 $(this) // Current element in the loop .attr('name') // Get the `name` attribute value .match(/\[(.*?)]/)[1]; // Match string inside square brackets 
  • $(this).attr('name') will get the value of the name attribute of the current input
  • \[(.*?)] will match anything inside the square brackets and add a line to the first captured group.
  • [1] in the matched array will give the string inside the square brackets.

 $(".kp").keyup(function() { $('input[name^="value"]').each(function() { console.log($(this).attr('name').match(/\[(.*?)]/)[1]); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' name='value[11]' class='kp'> <input type='text' name='value[22]' class='kp'> 
+7
source

As mentioned in another answer, you can access the current item in the callback using $(this) .

However, I would not rely on regex to extract an integer value.

Each function receives two parameters, the first is an index, the second is an element (equivalent to this ).

If the values ​​are sequential and start at 0, you can simply use the 1st parameter for each callback:

 <input type='text' name='value[0]' class='kp'> <input type='text' name='value[1]' class='kp'> $( ".kp" ).keyup(function() { $('input[name^="value"]').each(function(index, element) { console.log(index); }); }); 

If not, I would suggest adding the data attribute in html to contain the index:

 <input type='text' name='value[13]' data-index='13' class='kp'> <input type='text' name='value[106]' data-index='106' class='kp'> $( ".kp" ).keyup(function() { $('input[name^="value"]').each(function(index, element) { console.log($(element).data('index')); }); }); 
0
source

All Articles