I have a table of in which all the cells have a textbox to edit cell data. Now I want to use ajax to save data to a table for each keyup event. I have each textbox named as a 2d array that contains 2 ids, 1 id for each key, that I want save in a table.
<input type="text" name="txtfield[1][2]" />
now those 1 and 2 keys are ids that I want to save each in a separate column in a table.
Is there an easy way of getting those key values or should I use some string manipulation to get those values?
Any suggestions either in javascript or php would help.
It would probably be easier to name them
<input type="text" name="txtfield-1-2" />
Then, in PHP, you access them with
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
whatever($_POST["txtfield-$i-$j"]); /* or $_GET[...] */
In JavaScript, you do something like
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
whatever(document.getElementById("txtfield-" + i + "-" + $j).value);
I am assuming that these are in some kind of grid, so m
and n
are known. If not, Ek0nomik's solution would suit you better, although the regex should be \.*\[([0-9]+)\]\[([0-9]+)\]
(\[
and \]
should go outside of (...)
and quantifier +
should be added to allow indexes larger than 9) or, a bit more precise, ^txtfield\[([0-9]+)\]\[([0-9]+)\]$
.
You can get those values in both Javascript or PHP. Just use a regular expression:
An example (this could be made more specific if needed):
/.*(\[[0-9]\])(\[[0-9]\])/
PHP Example:
preg_match_all('/.*(\[[0-9]\])(\[[0-9]\])/', 'txtfield[1][2]', $matches, PREG_PATTERN_ORDER);
//Do something with $matches.
I'd prefer using jQuery, separating the data from the name value and avoiding regex.
<input type="text" data-apples="some_value" data-oranges="some_value" id="yourID" />
In jQuery:
var apples = $('#yourID').data('apples');
to retrieve the values needed.