获取表单外部的输入框的值

时间:2017-11-02 22:54:30

标签: php forms post input

我试图找出一种方法来获取不在表单中的输入框的值,并将其放在其下的表单的URL中。这就是我所说的:

        <div id="wrapper">
                <h1>[ <input type="text" name="to" id="to" placeholder="To"> ]</h1>
                <div id="menu">
                    <p class="welcome">Welcome, <b><?php echo htmlentities($user); ?></b></p>
                    <p class="logout"><a id="exit" href="#">Logout</a </p>
                    <div style="clear:both"></div>
                </div>

            <div id="chatbox"></div>
                <form name="message" action="../new_private.php?n=<?php echo $_POST['to']; ?>" method="post">
                    <input name="usermsg" type="text" id="usermsg" size="63">
                    <input name="submitmsg" type="submit" id="submitmsg" value="Send">
                    <input name="from" type="hidden" value="<?php echo $user; ?>">
                </form>
        </div>

当我以这种方式尝试时,我收到一个未定义的错误$_POST['to'] is not a valid index.

我想获得输入框的值&#34;到&#34;并将其放入其下的表单的URL中。我怎样才能做到这一点?

提前致谢!

亚历

1 个答案:

答案 0 :(得分:0)

在HTML5中,您可以在<input>之外添加<form>元素,方法是使用form attributeid格式的值。

例如......

<h1>[ <input type="text" name="n" id="to" placeholder="To" form="message"> ]</h1>

<!-- snip -->

<form id="message" action="../new_private.php" method="post">

这里唯一的区别是n字段将位于$_POST而不是$_GET

如果您确实需要网址中的值,那么您需要一些JavaScript。像这样的东西

<h1>[ <input type="text" name="to" id="to" placeholder="To"> ]</h1>

<!-- snip -->

<form name="message" action="../new_private.php" method="post">
  <!-- form contents, etc -->
</form>
<script>
(function() { // IIFE so as not to pollute the global scope
  const form = document.forms.message
  const action = form.action // original action
  document.getElementById('to').addEventListener('input', function() {
    form.action = action + '?n=' + encodeURIComponent(this.value)
  }, false)
})()
</script>