PHP_SELF& Javascript setAttribute

时间:2014-01-27 11:13:29

标签: javascript php setattribute

我在PHP中有以下代码:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <?php $value = $_POST['Field1'] ?>
    <input type="text" id="Field1" name="Field1" value="<?php echo $value ?>">
    <input type="button" value="ButtonValue" onclick="SubmitFunction()">
</form>

JavaScript中的一些功能:

<script>
    function SubmitFunction(){
        //... do some stuff here
        //But here I need to assign value to Field1:
        document.getElementById("Field1").setAttribute("value", "Some value");
        document.form.submit();
    }
</script>

当第一次加载此代码时,它表示存在未定义的索引Field1。这是绝对正确的。

但是当我使用SubmitFunction()将属性值设置为此字段时,页面重新加载并且仍然无法找到Field1!这是我的问题。

我注意到在纯HTML代码中,初始形式如下:

<form>
    <input type="text" id="Field1" name="Field1" value>
    <input type="button" value="ButtonValue" onclick="SubmitFunction()">
</form>

我的问题在哪里(大脑除外)?

1 个答案:

答案 0 :(得分:0)

 <script>
        function SubmitFunction(){
            //... do some stuff here
            //But here I need to assign value to Field1:
        document.getElementById("Field1").setAttribute("value", "Some value");
        document.form.submit(document.getElementById("Field1").getAttribute("value"));
        }
    </script>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <?php $value = $_POST['Field1'] ?>
        <input type="text" id="Field1" name="Field1" value="<?php echo $value?$value:''; ?>">
        <input type="button" value="ButtonValue" onclick="SubmitFunction()">
    </form>