PHP - 根据从选项中选择的内容获取值

时间:2015-08-03 12:04:38

标签: javascript php html select

<select class="selectpicker" name="mscr_type" id="mscr_type">

            <?php $fpp_type = '';
                  foreach ($getmilestone_cr as $mscr_list) {

                  $description = $mscr_list['FIX_PRJ_DESC'];//fetch  description

                    if ($fpp_type != $mscr_list['FIX_PRJ_TYPE']) {
                        if ($fpp_type != '') {
                            echo '</optgroup>';
                    }

                    if($mscr_list['FIX_PRJ_TYPE'] == 'MS'):
                        echo $fpp_label = "Milestone";
                    elseif($mscr_list['FIX_PRJ_TYPE'] == 'CR'):
                        echo $fpp_label = "Change Request(CR)";
                    endif;

                    echo '<optgroup label="'.$fpp_label.'">';

                    }

                    echo '<option value="'.$mscr_list['FIX_PRJ_TYPE'].'">'.htmlspecialchars($mscr_list['FIX_PRJ_NAME']).'</option>';
                    $fpp_type = $mscr_list['FIX_PRJ_TYPE'];    
                }

                    if ($fpp_type != '') {
                        echo '</optgroup>';
                    }
            ?>
</select>

以上代码输出:

<select class="selectpicker">
    <optgroup label="Picnic">
      <option value ="1">Mustard</option>
      <option value ="2">Ketchup</option>
      <option value ="3">Relish</option>
    </optgroup>
    <optgroup label="Camping">
      <option value ="4">Tent</option>
      <option value ="5">Flashlight</option>
      <option value ="6">Toilet Paper</option>
    </optgroup>
  </select>

如何根据从所选选项中选择的内容获取说明。例如,如果选择Mustard,则应填写输入值 有价值的&#39;芥末是黄色的&#39;。

尝试使用<select class="selectpicker" name="mscr_type" id="mscr_type" onchange="document.getElementById('mscr_description').value=this.options[this.selectedIndex].text">,但它取名而不是描述。

<label for="name" class="label">Description</label>  
<input type="text" disabled="" id="selectpicker_description" name="selectpicker_description" class="span3">

1 个答案:

答案 0 :(得分:0)

使用data-XXX属性将说明添加到HTML:

echo '<option value="'.$mscr_list['FIX_PRJ_TYPE'].'" data-description="'.htmlspecialchars($description).'">'.htmlspecialchars($mscr_list['FIX_PRJ_NAME']).'</option>';

然后你可以使用

onchange="updateDescription(this)"

使用Javascript函数:

function updateDescription(sel) {
    var output = document.getElementById('mscr_description');
    var desc = sel.options[sel.selectedIndex].getAttribute('data-description');
    output.value = desc;
}