user4495098
user4495098

Reputation: 93

Retrieve all inputs belonging to a certain array name into a jquery variable

Suppose I have this html:

<td>
  <input type="hidden" name="params[test][index]" value="0">
  <input type="hidden" name="params[test][name]" value="2">
  <input type="hidden" name="params[other][]" value="0">
  <input type="hidden" name="params[test2]" value="0">
</td>

And I want to grab all the inputs of the params array into my jquery as an array or as a json:

(not sure of the syntax but something like that)

var $params = { test => {index =>0, name=>2},other=>[0],test2=>0}; 

What should I do?

Upvotes: 1

Views: 63

Answers (1)

guest271314
guest271314

Reputation: 1

You can create a plain object, iterate input elements using $.each(), use .split() with RegExp

var params = {};

$.each($("td input"), function(_, el) {
  var param = el.name.split(/^\w+(?=\[)|\[|\]/).filter(Boolean).pop();
  params[param] = el.value;
});

console.log(params);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
  <input type="hidden" name="params[test][index]" value="0">
  <input type="hidden" name="params[test][name]" value="2">
  <input type="hidden" name="params[other][]" value="0">
  <input type="hidden" name="params[test2]" value="0">
</td>
</tr>
</table>

Edit, Updated

You can use if, if..else conditions and statements, RegExp to parse .name attributes to get expected result described at OP

var params = {};
var re = /\[|\]/g;

$.each($("td input"), function(_, el) {
  var param = el.name.match(/\[\]|\[\w+\]/g);
  var prop = param.shift().replace(re, "");
  if (param.length) {
    if (!(prop in params) && param[0] !== "[]") {
      params[prop] = {};
    }
    if (prop in params) {
      params[prop][param.shift().replace(re, "")] = el.value;
    } else if (param[0] === "[]") {
      params[prop] = [el.value];
    }
  } else {
    params[prop] = el.value;
  }
});

console.log(params);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<table>
  <tr>
    <td>
      <input type="hidden" name="params[test][index]" value="0">
      <input type="hidden" name="params[test][name]" value="2">
      <input type="hidden" name="params[other][]" value="0">
      <input type="hidden" name="params[test2]" value="0">
    </td>
  </tr>
</table>

Upvotes: 2

Related Questions