如何保持从选择字段中选择的值消失?

时间:2014-09-05 18:24:47

标签: php html select

我有以下代码:

<form method="post" enctype="multipart/form-data">
<table id="box-table-a" summary="PAGE HEADER" style='width:10%'>
<tr>
<th>
<?php 
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT Name FROM report ORDER BY Name ASC" ); 
echo "<b>Sort by Name:</b>&nbsp;\n"; 
echo " <select name='Name' onChange='submit(this.form)'>\n"; 
while( $row = mysqli_fetch_row( $PM )) { 
$sel = ( $table === $row[0] ) ? "id='sel' selected" : ""; 
printf( " <option %s value='%s'>%s</option>\n", $sel, $row[0], $row[0] ); 
    } 
    echo " </select>\n"; 
    ?> 
</th>
</tr>
</form>

选择完成后,选择框默认返回列表顶部的任何值(来自SELECT SQL查询...)。如何阻止这种情况发生并保留在选择框中选择的值,直到做出另一个选择?

2 个答案:

答案 0 :(得分:1)

更改下拉列表时表单重置的原因是因为您在选择框中有onChange事件。所以每当它改变它运行submit(this.form)。如果这是预期的功能,那么在代码下方将确保从提交时选择的下拉列表中的项目重置为所选项目。

<form method="post" enctype="multipart/form-data">
    <table id="box-table-a" summary="PAGE HEADER" style='width:10%'>
    <tr>
        <th>
            <?php 
                include('./db.php');
                $PM = mysqli_query($con, "SELECT DISTINCT Name FROM report ORDER BY Name ASC" ); 
                echo "<b>Sort by Name:</b>&nbsp;\n"; 
                echo " <select name='Name' onChange='submit(this.form)'>\n"; 
                while( $row = mysqli_fetch_row( $PM )) { 
                    // We should check if this value matches what they sent in the post
                    // Doing a nice litter ternary operation to put selected in the $selected variable if it matches.
                    $selected = array_key_exists('Name', $_POST) && $_POST['Name'] == $row[0] ? ' selected' : '';

                    // Now down here I added another %s which maps to the 3rd 
                    // parameter in printf, its the $selected variable from above.
                    printf( " <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0] ); 
                } 
                echo " </select>\n"; 
            ?> 
        </th>
    </tr>
</form>

我不确定是否给出了上下文,如果每次下拉更改都要提交表单。

如果不是这样,那么只需从select元素中删除属性onChange及其内容,它就会停止重置。

如果您希望在表单提交时由用户决定是否需要在表单内的某处添加提交按钮。

答案 1 :(得分:0)

嗯,首先,你应该停止混合PHP和HTML代码,这是令人毛骨悚然和令人困惑的。你也可能喜欢缩进的东西。它更简单明了。您的代码应如下所示:

<form method="post" enctype="multipart/form-data">
<table id="box-table-a" summary="PAGE HEADER" style='width:10%'>
<tr>
<th>
<?php 
include('./db.php');
    $PM = mysqli_query($con, "SELECT DISTINCT Name FROM report ORDER BY Name ASC" );
?>
    <b>Sort by Name:</b>
    <br> 
<select name='Name'>
<?php
while( $row = mysqli_fetch_row( $PM )) { 
    $sel = ( $table === $row[0] ) ? "id='sel' selected" : "";
    printf( " <option %s value='%s'>%s</option>\n", $sel, $row[0], $row[0] ); 
    }
?>
</select> 

</th>
</tr>
    <input type="submit" value="Submit">
</form>

如果你真的希望你的表单停止执行此值删除,则应删除此onChange='submit(this.form)'并使用submit button