1

I need to disable a button if there are no records returned in a db query. What i have is this:

  $cnt= mysql_num_rows($qry_resultcnt);
  if ($ttrec >=1)
  {
  echo "msgbox";
  document.getElementById("btn1").disabled = true;//disable insert button??
  }

but this returns a error message

   Parse error: syntax error, unexpected '='
  • 1
    @DhavalMarthak are you sure? It doesn't seem odd to try and execute JavaScript in the midst of PHP tags? – Sterling Archer Mar 27 '14 at 17:00
  • 1
    You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). – Quentin Mar 27 '14 at 17:00
  • This looks like a mixture of PHP and javascript. PHP can't execute Javascript and vice versa. If you enclose the javascript in script tags and echo it as a string It will probably get you what you want. But this should be handled by the template. – Chris Mar 27 '14 at 17:02

2 Answers2

1

You need to output suitable client side code. You can't just use client side JS directly in your PHP.

echo '<script>document.getElementById("btn1").disabled = true;</script>';

But you would probably be better off just setting the attribute:

echo '<button etc etc disabled>etc etc</button>';
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You're mixing php with javascript, which is not allowed. Try either of the two options below to escape your javascript from php.

$cnt= mysql_num_rows($qry_resultcnt);
if ($ttrec >=1) {
  echo "msgbox";
  echo '<script>document.getElementById("btn1").disabled = true;</script>';
}

Or....

$cnt= mysql_num_rows($qry_resultcnt);
if ($ttrec >=1) {
  echo "msgbox";
  ?>
  <script>
    document.getElementById("btn1").disabled = true;
  </script>
  <?php
}

Although for both options, I would recommend wrapping your JS in a self invoking function so that you are certainly firing it, like so...

echo '<script> (function() { document.getElementById("btn1").disabled = true; })(); </script>';

OR....

<script>
  (function() { 
    document.getElementById("btn1").disabled = true; 
  })();
</script>
Seth
  • 10,198
  • 10
  • 45
  • 68
  • i tryed this one"echo '';", but it disables the button even if the condition is false... – user3415003 Mar 27 '14 at 17:17