Create select using "for" cycle

Asked

Viewed 325 times

3

I’ve tested it in many ways, and I can’t create one <select/> with a for in PHP.

The doubt is simple, I have a for that goes from 1 until 48, and I need to return these 48 numbers on one select.

Does anyone know any way to put this together?

  • The number is the value of the select, the text of the select, or both?

3 answers

6

Using PHP:

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

?>
</select>       

5

Note: this is an answer to a previous revision of the question, in which the language was not specified and I assumed (erroneously) it was Javascript.

You can do this with DOM handling methods (createElement, appendChild, etc), but a simpler way is to create HTML as the same text 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 with DOM handling 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>

  • My concept of this is pretty basic, how would I implement this in a form::helper input from cakephp? <?= $this->Form->input('Semana',array(&#xA;'type' => 'select', &#xA;for($i=1 ; $i <49; $i++)&#xA;echo 'options' => '{$i} Semanas'&#xA;)); ?>

  • @Robertoschon Please cite this sort of thing in the question - not just the language used, but any library, framework, or whatever may influence the responses received. Initially I thought to give an example in jQuery, but I preferred to answer in pure JS to become more generic. Similarly, if the question is only quoted PHP you will only get "generic" answers, while the mention of cakephp can lead someone with experience on this platform to give you a more useful help. :)

1

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

You can use it like 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>

Browser other questions tagged

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