【问题标题】:JavaScript enable button not working in phpJavaScript启用按钮在php中不起作用
【发布时间】:2012-01-07 00:05:30
【问题描述】:

我使用 Javascript 来启用或禁用按钮,具体取决于输入值。我是 PHP 新手,所以我不知道为什么这不起作用。这是 PHP 代码:

<?php 
session_start();
include_once('header.php');
include_once('functions.php');

$_SESSION['userid'] = 1;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Microblogging Application</title>
</head>
vbody>

<?php
if (isset($_SESSION['message'])){
    echo "<b>". $_SESSION['message']."</b>";
    unset($_SESSION['message']);
}
?>
<form method='post' action='add.php'>
<p>Your status:</p>
<textarea name='body' rows='5' cols='40' wrap=VIRTUAL></textarea>

<input type="text" name="age" />
<input type="text" name="poscode" />
<input type="submit" name="submit" value="Post" disabled="disabled"/>




</form>

<script type="text/javascript">
$('input[name="age"], input[name="poscode"]').change(function(){
  if ($(this).val())
  {
    $("input[name='submit']").removeAttr('disabled');
  }
});

</script>
<?php
$posts = show_posts($_SESSION['userid']);

if (count($posts)){
?>
<table border='1' cellspacing='0' cellpadding='5' width='500'>
<?php
foreach ($posts as $key => $list){
    echo "<tr valign='top'>\n";

    echo "<td>".$list['body'] ."<br/>\n";
    echo "<small>".$list['stamp'] ."</small></td>\n";
    echo "</tr>\n";
}
?>
</table>
<?php
}else{
?>
<p><b>You haven't posted anything yet!</b></p>
<?php
}
?>
</body>
</html>

如何更改它,以便当 input 的值 =“foo”时,该按钮现在是可点击的。
提前致谢

-本

【问题讨论】:

  • 这里:&lt;script type="text/javascript"&gt; $('input[name="age"], input[name="poscode"]').change(function(){ if ($(this).val()) { $("input[name='submit']").removeAttr('disabled'); } }); &lt;/script&gt;
  • 让您知道,PHP 与 JavaScript 没有丝毫关系。所以,JS 不能在 PHP 中“工作”或“不工作”

标签: php javascript forms


【解决方案1】:

我无法理解您的问题,但如果您问的是我认为您在问什么(即“如果在页面加载时填充了表单,我如何启用按钮?”),请更改您的脚本如下:

$.ready(function(){
    $('input[name="age"], input[name="poscode"]').change(function(){
      if ($(this).val())
      {
        $("input[name='submit']").removeAttr('disabled');
      }
    }).change();
});

我添加了更改调用以触发更改事件处理程序,并将其包装在 jQuery 的就绪处理程序中。

【讨论】:

  • 请定义“不工作”,并定义您真正想要完成的工作。
  • 对不起,我只是希望当有人在输入中输入年龄时,该按钮不会被禁用。我不知道它是否在我的 php 中正确还是什么......
  • 你想在服务器端还是客户端?
  • 那么这可能与您定义事件处理程序时 jQuery 可能尚未初始化的事实有关。答案已更新。
【解决方案2】:

尝试使用 attr 函数,如下所示

$('#element').attr('disabled', true);

或者

$('#element').attr('disabled', false);

由于不同的浏览器对disbaled属性的处理方式不同,使用truefalse可以让jquery处理跨浏览器问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多