This time I really require assistance in creating a multiple text fields and save them in database. For now I know how create additional text fields with ‘add’ link, but if I create, let’s say, 10 text fields and populate them with text only the first one is added to database, other 9 not, and I need to know why?? (Probably I need to create a php function, which catches every click on ‘Add’ button and crates new array???)
1.array storing data:
array( "name" => "TEST",
"type" => "section"),
array( "type" => "open"),
array( "name" => "Button:",
"desc" => "Another text button",
"id" => $shortname."_testbutton",
"type" => "textbox",
"std" => ""),
array( "name" => "TEST2",
"type" => "section2"),
array( "type" => "close"),
2.Text fields:
<h2>
<a href="#" id="addbutton">Add</a>
</h2>
<div id="textfields">
<p>
<label for="<?php echo $value['id']; ?>"></label>
<input type="text" id="<?php echo $value['id']; ?>" size="20" name="<?php echo $value['id']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo stripslashes(get_settings( $value['id']) ); } else { echo $value['std']; } ?>" placeholder="Input Value" />
</p>
</div>
3.jQuery
jQuery(function($) {
var scntDiv = $('#textfields');
var i = $('#textfields p').size() + 1;
$('#addbutton').live('click', function() {
$('<p><label for="test_testbutton"></label><input type="text" id="test_testbutton" size="20" name="test_testbutton_' + i +'" value="" placeholder="Input Value" /> <a href="#" id="removebutton">Remove</a></p>').appendTo(scntDiv);
i++;
return false;
});
$('#removebutton').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
PS. That’s for WordPress theme options page.
EDIT!!!
I managed to create functioning loop which gets the number of created textfields, gets their values, puts everything back into textfields and preserves everything. I changed jQuery a bit:
name="test_testbutton_' + i +'"
to:
name="test_testbutton[]"
as Adam Erstelle suggested, and I looped everything in:
<?php
if (isset($_REQUEST['test_testbutton']) && is_array($_REQUEST['test_testbutton'])) {
$numbers = $_REQUEST['test_testbutton'];
foreach ($numbers as $number) {?>
<input type="text" id="<?php echo $value['id']; ?>" size="20" name="test_testbutton[]" value="<?php echo $number; ?>" placeholder="Input Value" /><a href="#" id="removebutton">Remove</a> <?php
}}?>
Now Everything is stored in array as it supposed to be, but I have a problem with feching textfields’ values to frontend and display them…????
What you could do is create an HTML array of values.
instead of
try
On the PHP side, $_POST[‘test_testbutton’] should an array of values. You can then work with this array as you need (keeping in mind that the array is the new complete list, so you may have to add/remove/edit elements in the persisted array)