I’m creating (and deleting) input fields dynamically in jQuery so they looks like:
<div id="new">
<div>
<input type="text" name="title1" value="" />
<input type="text" name="desc1" value="" />
</div>
<div>
<input type="text" name="title4" value="" />
<input type="text" name="desc4" value="" />
</div>
<div>
<input type="text" name="title7" value="" />
<input type="text" name="desc7" value="" />
</div>
</div>
As you can see, my fields names are not always like: 1,2,3 but they’re sometimes like 1,4,7.
My php code (part) to insert row into db table:
$i = 0;
global $wpdb;
$table_name = $wpdb->prefix . 'plugin';
$wpdb->insert( $table_name, array( 'title' => $_POST['title'], 'desc' => $_POST['desc'] ) );
jQuery:
var count = <?php echo $i; ?>;
$("#addnewbutton").click(function() {
count = count + 1;
$('#new').append('<div><input type="text" name="title'+count+'" value="" /><input type="text" name="desc'+count+'" value="" /></div>');
});
I know that I need to use “for” loop (probably) but I don’t know how to do it and I don’t want to add empty rows.
Regards
Taking a purely PHP approach, you can run a loop through $_POST and check if the keys begin with ‘title’, split the string into two parts: the ‘title’ and the {number}. Check if a key with ‘desc{number}’ exists, if it does…you know what to do.
You can also process the form with JavaScript/JQuery first so it’s really nice when PHP gets it by a JSON that has a ‘title’ obj and a ‘desc’ obj.