繁体   English   中英

基于 GET 预选项目

[英]Pre-Select an Item based on GET

我根据$_GET的值在列表框中预 select 一个项目。

例如:带有选项 1、2、3 的选择框。 从 url 我得到值 2。如何预选这个值? <option...selected>...</>的方式太复杂了。 我只想声明预先选择了哪个选项,例如<select selected="2">

我的答案中if语句数量较少的解决方案是最后一个。

不幸的是,没有办法这样做<select selected="2"> 你必须做这样的事情:

<select name="select">
  <option value="1"<?php if ( $_GET['select'] == '1' ): ?> selected="selected"<?php endif; ?>>Option 1</option>
  <option value="2"<?php if ( $_GET['select'] == '2' ): ?> selected="selected"<?php endif; ?>>Option 2</option>
  <option value="3"<?php if ( $_GET['select'] == '3' ): ?> selected="selected"<?php endif; ?>>Option 3</option>
</select>

如果您允许多重,我将使用in_array并确保select元素的名称指定它是一个数组(使用方括号)。

<select multiple="multiple" name="multi_select[]">
  <option value="1"<?php if ( in_array('1', $_GET['multi_select']) ): ?> selected="selected"<?php endif; ?>>Option 1</option>
  <option value="2"<?php if ( in_array('2', $_GET['multi_select']) ): ?> selected="selected"<?php endif; ?>>Option 2</option>
  <option value="3"<?php if ( in_array('3', $_GET['multi_select']) ): ?> selected="selected"<?php endif; ?>>Option 3</option>
</select>

作为替代方案,您可以使用 PHP array来创建选项,并使用foreach循环来创建option

<select name="select">
<?php

$options = array(
  1 => 'Option 1',
  2 => 'Option 2',
  3 => 'Option 3'
);

foreach ( $options as $value => $name )
{
  echo '<option value="' . $value . '"' . ( $_GET['select'] == $value ? ' selected="selected"' : '' ) . '>' . $name . '</option>';
}

?>
</select>

没有办法让选定的标签指示选择了哪一个。 它必须通过选项标签来完成。

您是否考虑过遍历选项?

$desiredSelect = $_GET['desired'];

foreach( array('option-value'  => 'option-text',
               'option-value2' =>'option-text2' ) as $val => $test )
{
    echo "<option value=\"$val\" ";
    if( $val == $desiredSelect ) echo "selected = \"selected\"";
    echo ">$text</option>";
}

如果请求是一个 get,一个选项可以是注入一个简单的 JavaScript/jQuery 脚本,以便在 DOM 就绪时触发:

如果请求被获取,则将此代码注入响应 HTML:

$(function(){
    $('#selectBox').val(selectedItemValue);
});

就是这么简单。 :)

实际上,您有两种方法:第一种是将每个元素与选定的元素进行比较(就像 @Francois Deschenes 和 @cwallenpoole 一样); 第二个是解决方法,因此不是很好,但更容易实现。 列表形成后,您可以使用 javascript 将所选项目设置为需要:

<script type="text/javascript">
$(function() {
    $('select[selected]').val(function() {
        return $(this).attr('selected')
    })
});
</script>
<select selected="7">
    <option value="1">1</option>
    <!-- ... -->
    <option value="10">10</option>
</select>

另一个非 if 非 js 版本可能是这样的

<?
$res = array($_GET["selected"] => " selected='selected'");    
?>


<select name="select">
  <option value="1"<? echo $res['1']; ?>>Option 1</option>
  <option value="2"<? echo $res['2']; ?>>Option 2</option>
  <option value="3"<? echo $res['3']; ?>>Option 3</option>
</select>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM