javascript选择表单选项

时间:2013-09-14 11:34:50

标签: javascript php forms options selected

<div id="pdf">
    <script type="text/javascript">
        function get_pdf_file( elem ) {
            var filename = elem.options[elem.selectedIndex].value;
            var file_id = elem.options[elem.selectedIndex].id;
            var id = elem.options[elem.selectedIndex].index;
            // output some stuff to console: it works
            console.log( 'get_pdf_file( elem ) filename id: ' + id );
        }
    </script>
    <div id="choose_pdf">
        <form id="select_pdf_file">
            <select name="pdf_file" onChange="get_pdf_file( this )">
                <?php
                    for ( $i = 0; $i < $count_filenames; $i++ ) {
                        if ( $i == 0 ) {
                            echo '<option id="file_' . $i . '" value="' . $filenames[$i] . '" selected >' . $filenames[$i] . '</option>';
                            $pdf_file = $filenames[$i];
                        } else {
                    echo '<option id="file_' . $i . '" value="' . $filenames[$i] . '">' . $filenames[$i] . '</option>';
                        }
                    }
                    # output from above:
                    #<option id="file_1" value="tutorial_1.pdf" selected >tutorial_1.pdf</option>
                    #<option id="file_2" value="tutorial_2.pdf" >tutorial_2.pdf</option>
                    # ...
                    # ...
                ?>
            </select>
        </form>
    </div>
    <!-- here is the container to output the selected file "$pdf_file" (see above)-->
    <object width="1000" height="803" type="application/pdf" data="<?php echo $pdf_file ?>?#zoom=58.7&scrollbar=1&toolbar=1&navpanes=1" id="pdf_content">
        <p>Insert your error message here, if the PDF cannot be displayed.</p>
    </object>
</div>

变量$count_filenames是名为$filenames的数组中包含各种.pdf文件名称的元素数...

相信我会错过一些代码作为用户操作选择tutorial_2.pdf,例如总是输出相同的文件,即tutorial_1.pdf ......

请帮助解决这个问题!

2 个答案:

答案 0 :(得分:0)

你也应该在其他情况下做同样的$pdf_file = $filenames[$i];

 else {
            echo '<option id="file_' . $i . '" value="' . $filenames[$i] . '">' . $filenames[$i] . '</option>';
$pdf_file = $filenames[$i];
        }

答案 1 :(得分:0)

更好,

for ( $i = 0; $i < $count_filenames; $i++ ) {
    if ( $i == 0 ) 
        echo '<option id="file_' . $i . '" value="' . $filenames[$i] . '" selected >' . $filenames[$i] . '</option>';
    else 
        echo '<option id="file_' . $i . '" value="' . $filenames[$i] . '">' . $filenames[$i] . '</option>';
    $pdf_file = $filenames[$i];
}