2011-06-11 47 views
0

我想双击链接自动填充两个输入元素。下面是我使用的代码:使用数据库条目自动填充HTML表单

<script> 

    function autoFill(depart_from, depart_to) { 
     document.getElementById('depart_from').value = depart_from; 
     document.getElementById('depart_to').value = depart_to; 
    } 

</script> 

这里是链接:

...

echo "<tr class='odd'>"; 
echo "<td><span class='hover'><ahref='#'onClick='autoFill(" . $row['departure'] . ", " . $row['destination'] . "return false;'>" . $row['departure'] ." » ". $row['destination'] . "</a><span></td>"; 
echo "</tr>"; 

不能得到它的工作!我究竟做错了什么?

感谢名单!

回答

0

对于初学者来说,间距打破了你的锚标记:

<ahref='#'onClick='autoFill(

应该是:

<a href='#' onClick='autoFill(

此外,你永远不会关闭该功能和独立的语句以分号:

autoFill(" . $row['departure'] . ", " . $row['destination'] . "return false; 

应该是:

autoFill(" . $row['departure'] . ", " . $row['destination'] . ");return false; 

最后,你可能想在引号来包装这些方法参数:

autoFill(" . $row['departure'] . ", " . $row['destination'] . ");return false; 

应该是:

autoFill('" . $row['departure'] . "', '" . $row['destination'] . "');return false; 

可能还有更多。要记住的一件事是尝试不使用echo语句来发射大块HTML。它使代码不那么容易阅读,更重要的是它增加了另一层“字符串化”,这使得在字符串中引用引号稍微困难一些。

+2

将PHP变量传递给javascript的正确方法是使用'json_encode'。不''addslashes',不''htmlentities'(或'htmlspecialchars'),而且绝对不是什么。 – Halcyon 2011-06-11 13:37:19

+0

@Frit van Campen:的确,OP的代码还有很多工作要做。 – David 2011-06-11 13:39:29

+0

Thanx!我会尝试一种不同的方法。必须有更干净的方式来做到这一点! – Ismailp 2011-06-11 14:06:06

0

您的a标签上的间距错了,您需要在a href之间有空格。

你永远不会关闭括号内为函数调用,我想你可能需要把参数引号,根据其类型:

autoFill('" . $row['departure'] . "', '" . $row['destination'] . "'); return false;'