Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery PHP Handle input array

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 say, I wanna get the $x/$y variable of array. (with .val(); function I get the string inside textbox)

Is there a way? Thank you!

like image 552
L. Soprano Avatar asked May 25 '16 12:05

L. Soprano


1 Answers

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

$(this)                       // Current element in the loop
    .attr('name')             // Get the `name` attribute value
    .match(/\[(.*?)]/)[1];    // Match string inside square brackets
  1. $(this).attr('name') will get the name attribute value of the current input
  2. \[(.*?)] will match anything inside the square brackets and add the string into first captured group
  3. [1] on matched array will give the string inside 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'>
like image 92
Tushar Avatar answered Nov 04 '22 16:11

Tushar