Reputation: 71
I select 2 text fields and input 'alpha' on the first text field and second on the 'beta'. When I display it on the next page It only shows the second value which is 'beta'. What is the problem with my code? I already foreach the the variable that holds the data.
This is the view for form. (jscript)
<script type="text/javascript">
$(document).ready(function() {
$('#bookinfo_adult').change(function(){
var num = $('#bookinfo_adult').val();
var i = 0;
var html = '';
for (i=1;i<=num;i++) {
html += 'Adult ' + i + ': <input type="text" name="passenger-' + i + '"/><br/>';
}
$('#List').html(html);
});
});
</script>
This is the form
Adult:
<select id="bookinfo_adult" name="bookinfo_adult">
<option value="0">- SELECT -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<div id="List"></div>
This is controller
for ($i=1;$i<=$data['num'];$i++) {
//concatinate number of fields to a variable
$name=array();
$name=$this->input->post('passenger-'.$i);
$value=array();
$value='val'.$i;
$data['bookinfo_passengers']=array();
$data['bookinfo_passengers']=array($value=>$name);
}
This is whats on my display view
for($a=1;$a<=$num;$a++){
foreach($bookinfo_passengers as $value=>$name)
{
echo $value.'='.$name;
}
}
Upvotes: 0
Views: 271
Reputation: 17940
You are restarting the array every loop and you are overriding the old data with the new one:
for ($i=1;$i<=$data['num'];$i++) {
//concatinate number of fields to a variable
$name=array();
$name=$this->input->post('passenger-'.$i);
$value=array();
$value='val'.$i;
$data['bookinfo_passengers']=array(); ---> **put this outside of the loop**
$data['bookinfo_passengers']=array($value=>$name); ---> this will override the previous data.
}
try this:
$data['bookinfo_passengers']=array();
$tmp = array();
for ($i=1;$i<=$data['num'];$i++) {
//concatinate number of fields to a variable
$name=array();
$name=$this->input->post('passenger-'.$i);
$value=array();
$value='val'.$i;
$tmp[$value] = $name;
}
$data['bookinfo_passengers']=$tmp;
Then use it like:
foreach($data['bookinfo_passengers'] as $value=>$name)
{
echo $value.'='.$name;
}
Upvotes: 1