Create select using cycle "for"

3

I tested it in many ways, and I can not create a <select/> with a for in PHP.

The question is simple, I have a for ranging from 1 to 48 , and I need to return those 48 numbers to a select .

Does anyone know a way to put this together?

    
asked by anonymous 14.04.2015 / 16:14

3 answers

6

Using PHP:

<select name="exemplo" id="exemplo"> 
<?php
for($i=1 ; $i <49; $i++)
        echo"<option value='$i'>'$i'</option>";

?>
</select>       
    
14.04.2015 / 16:36
5
  

Note: This is a response to a previous revision of the question, in which the language was not specified and I assumed (erroneously) to be JavaScript.

You can do this with DOM manipulation methods ( createElement , appendChild , etc), but a simpler way is to create HTML as text itself and insert it into innerHTML of your select :

var html = "";
for ( var i = 1 ; i <= 48 ; i++ ) {
  html += '<option value="' + i + '">' + i + "</option>";
}
document.getElementById("meuSelect").innerHTML = html;
<select id="meuSelect"></select>

Alternative to DOM manipulation methods:

var meuSelect = document.getElementById("meuSelect");
for ( var i = 1 ; i <= 48 ; i++ ) {
  var opcao = document.createElement("option");
  opcao.setAttribute("value", i);
  opcao.textContent = "" + i;
  meuSelect.appendChild(opcao);
}
<select id="meuSelect"></select>
    
14.04.2015 / 16:20
1

Although not specified, the author seems to be using cakePHP,

You can use this:

$array = array(
     '' => 'Selecione...'
);

for ($i = 1; $i < 49; ++$i) {
    if ($i === 1) {
        $array['1'] = '1 Semana';//Singular :)
    } else {
        $array[(string) $i] = $i . ' Semanas';
    }
}

echo $this->Form->input('Semana', array(
    'type' => 'select',
    'options' => $array
));

The result will be something like:

<div class="input">
    <label for="Semana">Field</label>
    <select id="Semana" name="data[User][Semana]">
        <option value="">Selecione...</option>
        <option value="1">1 Semana</option>
        <option value="2">2 Semanas</option>
        ...
    </select>
</div>
    
22.04.2015 / 17:40