当我返回页面时,下拉菜单不会保持选中状态

时间:2015-06-12 14:07:15

标签: php html

任何想法,为什么以下脚本的下拉菜单不会保留在选定的值上:      

 if (isset($_POST['Submit1'])) {
     $frequency = $_POST['frequency'];
     $fileName = 'ConfigurationFile.txt';

     $lines = file($fileName);

     $lines[0]="Center_frequency= ". $frequency."\n";

     file_put_contents($fileName, implode($lines));

 } else {

     $fileName = 'ConfigurationFile.txt';

     $lines = file($fileName);

     $frequency=explode(" ",$lines[0]);
     $frequency=$frequency[1];
 }
 ?>

但是如果我把我的号码放在引号中,意思是

 <?php

 if (isset($_POST['Submit1'])) {
     $frequency = $_POST['frequency'];
     $fileName = 'ConfigurationFile.txt';

     $lines = file($fileName);

     $lines[0]="Center_frequency= ".'"'. $frequency.'"'."\n";

     file_put_contents($fileName, implode($lines));

 } else {

     $fileName = 'ConfigurationFile.txt';

     $lines = file($fileName);

     $frequency=explode("\"",$lines[0]);
     $frequency=$frequency[1];
 }
 ?>

它会像魅力一样工作,意味着所选值将保留,下拉菜单不会转到列表中的第一个值。 这是下拉菜单的HTML代码

     <form action="test.php" name="Calculation" method="post">
     Center Frequency: 
     <select name="frequency" >

     <?php $attr= 'selected="selected"'; ?>

    <option value="4.463" <?php echo $frequency  == '4.463' ? $attr :  ''; ?>>4.463</option>
    <option value="5.2625" <?php echo $frequency  == '5.2625' ? $attr : ''; ?>>5.2625 </option>
    <option value="9.33"   <?php echo $frequency  == '9.33' ? $attr : ''; ?>>9.33 </option>
    <option value="13.5"   <?php echo $frequency  == '13.5' ? $attr : ''; ?>>13.5 </option>
    <option value="16.15"  <?php echo $frequency  == '16.15' ? $attr : ''; ?>>16.15 </option>
    <option value="24.525" <?php echo $frequency  == '24.525' ? $attr : ''; ?>>24.525</option>
    <option value="26.275" <?php echo $frequency  == '26.275' ? $attr : ''; ?>>26.275</option>

   </select>

    <Input Type = "Submit" Name ="Submit1" Value = "Save Parameters">

    </form>

2 个答案:

答案 0 :(得分:3)

$fileName = 'ConfigurationFile.txt';

        $lines = file($fileName);

        $frequency=explode(" ",$lines[0]);
        $frequency=$frequency[1];

        var_dump($frequency);
        //string(5) "13.5 " <== space

<强>溶液

$fileName = 'ConfigurationFile.txt';

        $lines = file($fileName);

        $frequency=explode(" ",$lines[0]);
        $frequency=trim($frequency[1]); //trim function

http://php.net/manual/pl/function.trim.php

答案 1 :(得分:3)

你的爆炸功能没有问题,这个问题是你的$ frequency返回一个字符串,右边有一个额外的空白区域。试试这个:

if (isset($_POST['Submit1'])) {
     $frequency = $_POST['frequency'];
     $fileName = 'ConfigurationFile.txt';

     $lines = file($fileName);

     $lines[0]="Center_frequency= ". $frequency."\n";

     file_put_contents($fileName, implode($lines));

 } else {

     $fileName = 'ConfigurationFile.txt';

     $lines = file($fileName);

     $frequency=explode(" ",$lines[0]);
     $frequency=trim($frequency[1]);
 }

&GT;

它应该有效