开发者

In an HTML form, I need to generate incrementally increasing values in the dropdown options of a select tag

Here's what I need to write for a bunch of dropdown menus:

<select>
    <option value="23">23</option>
    <option value="23.5">23.5</option>
    <option value="24">24</option>
    <option value="24.5">24.5</option>
    [etc...]
</select>

It needs to increase by .5 for every option.

The etc. part is where I need to repeat the process like 40+ times. There are multiple selects on the page as well with values starting and stopping at diff开发者_Python百科erent numbers.

These numbers will be static and will not change once generated. So the values and HTML code just need to built once and it's good to go. The site is powered using PHP.

I don't want to have to hand-code all of this code one option after another option! I'm not sure what the easiest way to do this is. Regex? JS?


$total = 40;
$value = 23.00;

$HTML = '<select>';

for($i = 0; $i < $total; $i++)
{
    $HTML .= '<option value="'.$value.'">'.$value.'</option>';
    $value += 0.5;
}

$HTML .= '</select>';


If you're just looking to have it print out the data one time I'd go with a language like Python. You can generate them dynamically at run time with JavaScript if you'd like to, but beware that this will reduce functionality for users who disable JS. In Python then:

for num in range(25, 50):
  print r'<option value="%d">%d</option>' % (num, num)
  print r'<option value="%d.5">%d.5</option' % (num, num)

That should give you as many as you need, and be adaptable.

Also, for what it's worth, you should employ a more powerful scripting language (PHP, ASP, Ruby, etc) in page to do this kind of thing if at all possible, not create a bunch of static, hard coded files. Those are going to be difficult to maintain later.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜