Reputation: 185
I have got the following code which is input form.
<div class="input_wrap">
<div class="questions-field row">
<label class="col-md-12" for="">
<input type="text" name="questions[]" class="form-control">
</label>
</div>
<button class="add_field_button">Add More input </button>
</div>
I am using jQuery to generate new inputs after clicking on button. JS looks like as follow:
$(document).on("click", ".remove_field", function () {
$(this).parent().remove();
});
$(document).ready(function () {
$(".add_field_button").click(function (e) {
e.preventDefault();
$(".input_wrap>div").append('<label class="col-md-12"for=""><a href="#" class="remove_field">Remove</a><input type="text" name="questions[]" class="form-control col-md-10"></label>'); //add input box
});
});
So everythings works fine, i use PHP to get array ( questions[] ) which contain filled inputs.
So when i filled up 5 inputs i get array that looks like:
Array
(
[0] => rgerg
[1] => qwd
[2] => ffr
[3] => fffffffffffffff
[4] => ggggggggggggg
)
What i want is to add NOT just one but 2 inputs dynamically where first one would be the question and second one the answer. Something like:
Array
(
[0] => array('rgerg','text associated to rgerg')
[1] => array('qwd','text associated to qwd')
[2] => array('ffr','text associated to ffr')
.
.
.
)
how it can be done ? Thanks in advance.
Upvotes: 1
Views: 63
Reputation: 61
You can add question and corresponding answer as mentioned below:
<input type="text" name="quiz[0][question]" class="form-control">
<input type="text" name="quiz[0][answer]" class="form-control">
<input type="text" name="quiz[1][question]" class="form-control">
<input type="text" name="quiz[1][answer]" class="form-control">
<input type="text" name="quiz[2][question]" class="form-control">
<input type="text" name="quiz[2][answer]" class="form-control">
$_POST will return below array:
Array
(
[quiz] => Array
(
[0] => Array
(
[question] => ques1
[answer] => ans1
)
[1] => Array
(
[question] => ques2
[answer] => ans2
)
[2] => Array
(
[question] => ques3
[answer] => ans3
)
)
)
Upvotes: 1
Reputation: 193261
You could associate question with corresponding answer if you give both fields same index in their names. For example, with this name
attributes
Question:
<input type="text" name="questions[0][]" value="Question 1" />
Answer:
<input type="text" name="questions[0][]" value="Answer 1" />
(yes, names are absolutely the same)
Resulting $_POST
in PHP side will have desired structure:
Array
(
[questions] => Array
(
[0] => Array
(
[0] => Question 1
[1] => Answer 1
)
[1] => Array
(
[0] => Question 2
[1] => Answer 2
)
)
)
Of course you need to increment index in the name with each question:
name="questions[0][]" // First question
name="questions[1][]" // Second question
name="questions[2][]" // Third question
Upvotes: 1