2017-07-24 95 views
2

这是我创建的动态列表,我想将它传递给输入值。 这是我的代码。获取动态文本的值将其传递给输入值

<?php 
    $conn = mysqli_connect("localhost", "root", "","dbStudent"); 
    $query = mysqli_query($conn, "select * from tblaccounts"); 
    while ($row = mysqli_fetch_array($query)) 
    { 
    ?> 
    <ul> 
    <li onclick="GettingSurname" id="Surname"><?php echo $row["Lastname"]; ?></li> 
    </ul> 
    <?php 
    } 
    ?> 

它会显示在输入值,如果我点击了姓。

<input type="text" name="username" id="username"> 

如果我选择了姓氏,它会将它传递给输入值。

<script type="text/javascript"> 
    function GettingSurname() 
    { 
     document.getElementById("username").value = Surname; 
    } 
</script> 
+1

你忘了'()''使用的onclick = “GettingSurname()”' – Satpal

+0

你在哪里定义'Surname',您正在使用在'GettingSurname()'函数中?顺便说一句,你不应该在循环之前有'

    '而在循环之后有'
'?否则,您只需创建一个新列表,每个用户只包含一个项目。 –

回答

1

假设你什么的li文本内容传递作为用户名的文本,您需要将当前元素即this内联事件处理程序。使用textContent属性来设置值。

<li onclick="GettingSurname(this)"><?php echo $row["Lastname"]; ?></li> 

脚本

function GettingSurname(elem) 
{ 
    document.getElementById("username").value = elem.textContent; 
} 

注意:您用相同的ID id="Surname"创造元素,在HTML标识必须是唯一

1

你出现在while循环要创建行,所以这最终可能会创建具有相同ID(姓氏)的多行。相反,你可以只在传递名称在这样的函数中的参数:

<li onclick="GettingSurname('<?php echo json_encode($row["Lastname"]); ?>')"><?php echo $row["Lastname"]; ?></li> 

(请确保您编码的功能参数的姓氏,以防万一有人叫奥康纳或者如果有人把XSS黑客作为自己的姓氏)

然后在JavaScript这样做:

function GettingSurname(surname){ 
document.getElementById("username").value = surname; 
} 
1

另一个和更更好的方式来达到同样的目标是:

PHP:

<?php 
$conn = mysqli_connect("localhost", "root", "","dbStudent"); 
$query = mysqli_query($conn, "select * from tblaccounts"); 

//Take a counter variable to assign dynamic IDs to the HTML element iterated in the while loop 
$counter = 0; 
while ($row = mysqli_fetch_array($query)) 
{ 
    ?> 
    <ul> 
     <li onclick="GettingSurname('<?php echo $row["Lastname"]; ?>')" id="Surname_<?php echo $counter; ?>"> 
      <?php echo $row["Lastname"]; ?> 
     </li> 
    </ul> 
<?php 
    $counter++; 
} 
?> 

的Javascript:

<script type="text/javascript"> 
function GettingSurname(surname_value) 
{ 
    document.getElementById("username").value = surname_value; 
} 
</script> 
相关问题