将PHP变量传递给Javascript动态添加了文本框

时间:2009-10-12 08:59:05

标签: php javascript

我有一个像这样的javascript函数:

function addfamily(divName){
    var newdiv = document.createElement('div');
    newdiv.innerHTML = '<input type="text" name="family[]" size="16">';
    document.getElementById(divName).appendChild(newdiv);
}

动态地将文本框添加到表单和php脚本,如下所示:

<?php
$result_family = mysql_query("SELECT * FROM family_member where login_id='$_SESSION[id]'");

$num_rows_family = mysql_num_rows($result_family);

if ($num_rows_family>0) {

   while($row_family = mysql_fetch_assoc($result_family)){

   echo "<script language=javascript>addfamily('family');</script>";
   }
}

使用此代码可以很好地添加文本框。 我只需要知道如何通过将php变量$row_family[name]传递给函数和文本框的值来将动态值设置为文本框值? 请帮忙

1 个答案:

答案 0 :(得分:2)

由于您想要传递Div的名称以及$ row_family ['name'],您的javascript函数应该看起来像

function addfamily(divName,familyName){
  var newdiv = document.createElement('div');
  newdiv.innerHTML = "<input type='text' name='family[]' size='16' value=" + familyName + ">";
  document.getElementById(divName).appendChild(newdiv);
}

然后来自PHP的调用应该像

echo "addfamily('family',$row_family['name']);";

HTH