property name textarea name="Q1" ate name="Q20" + php

Asked

Viewed 61 times

2

I need the property name="q1" generates a sequence, like this:

<textarea name="q1"></textarea>
<textarea name="q2"></textarea>
<textarea name="q3"></textarea> 
.
.
. <!-- // Até -->
<textarea name="q20"></textarea>  

My code below:

forEach($resultado as $y){ ?>
    <label class="fs-field-label fs-anim-upper" for="q1"><?php echo $y['ipco_descr_item']; ?></label> 

    <textarea rows="3" cols="30" class="fs-anim-lower" id="q1" **name="q1"** placeholder="Resposta"> </textarea>
    <div id="resposta"></div>

    <?php 
    }
  • Wants to generate several <textarea> each with its own qx? This number comes from where? do $resultadothat is being iterated?

2 answers

4


If you want to repeat that line you can create a loop there and concatenate the number that is being iterated.

forEach($resultado as $y){ ?>
    <label class="fs-field-label fs-anim-upper" for="q1"><?php echo $y['ipco_descr_item']; ?></label> 
    <?php 
    for($i = 1; $ < 21; $i++){
        echo '<textarea rows="3" cols="30" class="fs-anim-lower" id="q1" name="q'.$i.'" placeholder="Resposta"> </textarea>';
    }
    ?>
    <div id="resposta"></div>

    <?php 
    }

The cycle for goes from 1 to 20 and in the property that wants to join the number can do name="q'.$i.'" to add the number to the letter.

4

You better do it like this:

foreach($resultado as $y){ ?>
   <label class="fs-field-label fs-anim-upper" for="q[]"><?php echo $y['ipco_descr_item']; ?></label> 
   <textarea rows="3" cols="30" class="fs-anim-lower" id="q[]" name="q[]" placeholder="Resposta"> </textarea>
  <div id="resposta"></div>
<?php 
}

And receive the data thus:

if (isset($_POST['q'])){
  foreach ($_POST['q'] as $key => $value) {
     echo 'field: q'.$key.'<br>';
     echo 'value: '.$value.'<br><hr><br>';
  }
}

But if you find it hard to do it that way, you can generate your code that way:

$i = 1;
foreach($resultado as $y){ ?>
   <label class="fs-field-label fs-anim-upper" for="q<?=$i?>"><?php echo $y['ipco_descr_item']; ?></label> 
   <textarea rows="3" cols="30" class="fs-anim-lower" id="q<?=$i?>" name="q<?=$i?>" placeholder="Resposta"> </textarea>
  <div id="resposta"></div>
<?php 
  $i++;
}
  • Thank you Kadu, it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.