简体   繁体   English

如何在PHP echo中使用JavaScript .value

[英]How to get JavaScript .value working in PHP echo

I got a question to a JavaScript code. 我有一个JavaScript代码的问题。 I got an HTML form: 我有一个HTML表单:

<form action="getValue.php" method="post" id="myform">
    <input type="text" id="mybox" name="mybox" />
    <input type="submit" id="submit" name="submit" value="Submit" />
</form>

I want to alert the value by clicking submit button. 我想通过单击“提交”按钮来提醒值。 For this I use this code: 为此我使用此代码:

$(document).ready(function(){
    $('#myform').submit(function(event){
        alert(document.getElementById('mybox').value);
    });
});

If I type in for example "123" it alerts "123". 如果我输入例如“123”,它会提醒“123”。 Okay, this works. 好的,这很有效。 Now I want to run this JavaScript code in PHP echo . 现在我想在PHP echo运行这个JavaScript代码。 For this I tried this: 为此,我尝试了这个:

if(isset($_POST['submit'])){
    echo "<script>alert(document.getElementById('mybox').value);</script>";
}

If I now type in "123" it returns " ". 如果我现在输入“123”,则返回“”。 So nothing returns. 没有回报。 Can someone explain me why this is or how to fix this? 有人可以解释一下为什么会这样或如何解决这个问题?

Cheers 干杯

EDIT: It is all in the same file (getValue.php) 编辑:它都在同一个文件中(getValue.php)

Your text box will not be populated when the page has been reloaded. 重新加载页面时,不会填充您的文本框。

Try echo'ing the actual post value. 尝试回显实际的帖子值。

if(isset($_POST['submit'])){
    echo "<script>alert('" . $_POST['mybox'] . "');</script>";
}

Edit: 编辑:

As you pointed out that you were new to PHP & JavaScript I thought I'd mention that you seem to be using half jQuery and half non-jQuery... 当你指出你是PHP和JavaScript的新手时,我想我会提到你似乎在使用半jQuery和一半非jQuery ......

For example instead of using 例如,而不是使用

document.getElementById('mybox').value

You can use 您可以使用

$('#mybox').val();
echo '<script type="text/javascript">alert("Data has been submitted to ' . $_POST['mybox'] . '");</script>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM