Reputation: 182
I have 20 columns in my database table.
The user can enter any amount in the input field.
I am creating input fields using jQuery, and it works fine, but the problem is that when I create less than 20 fields and submit form by POST to my PHP file, it gives me an error because the field name does not exist.
<span id="response"></span>
<script>
var countBox =2;
var boxName = 0;
function addInput()
{
if(countBox<=20){
var boxName="member"+countBox;
document.getElementById('response').innerHTML+='<div class="row"><div class="col-sm-12"><label id="labeltext">Name of Member '+countBox+'</label> <input type="text" id="'+boxName+'" name="'+boxName+'" placeholder="Name of Member" ></div></div>';
countBox += 1;
}
}
</script>
<div class="row"><div class="col-sm-12">
<input class="btn btn-info" type="button" name="Member" value="Add Member" onclick="addInput()">
</div></div>
PHP (there are 20):
$_POST['Member']
Upvotes: 0
Views: 272
Reputation: 669
So it looks like in your addInput loop you are creating 20 inputs named member0,member1,member2... but in your php you are looking for the attribute "Member" in the $_POST data. "Member" is the name of the button, not the inputs.
Try something like:
<span id="response"></span>
<script>
var countBox =2;
var boxName = 0;
function addInput()
{
if(countBox<=20){
var boxName="Member[]";
// or var boxName="Member["+countBox+"]";
document.getElementById('response').innerHTML+='<div class="row"><div class="col-sm-12"><label id="labeltext">Name of Member '+countBox+'</label> <input type="text" id="'+boxName+'" name="'+boxName+'" placeholder="Name of Member" ></div></div>';
countBox += 1;
}
}
</script>
<div class="row"><div class="col-sm-12">
<input class="btn btn-info" type="button" name="Member-btn" value="Add Member" onclick="addInput()">
</div></div>
Upvotes: 0
Reputation: 323
$array = array();
for ( $i = 0; $i < 20 ; $i++ ) {
$array['Member'.$i] = array_key_exists('Member'.$i , $_POST) ? $_POST['Member'.$i] : "";
}
I didn't test the code but it might be something like this.
Now you had to push $array into your database.
Upvotes: 0
Reputation: 5589
In the php script you should check the $_POST[] to see which are the values you are receiving and process the data according to that.
You can use array_key_exists to see if the key of the value exists in the array.
On another side, if you want to receive the 20 values, you have to send them from the html. In this case values not entered by the user would go with en empty value: "".
Upvotes: 0