1

是否可以自动从下拉列表中获取第一项到页面加载时的输入?例如,下拉列表有 2 个选项:happy& sad。当页面加载时,我想happy在页面加载时输入。到目前为止,我得到了一个空输入,用户需要在下拉列表中选择选项。

jQuery代码:

<script type="text/javascript">
    $(document).ready(function() { 
        $("#username_select").change(function() { 
            $("#username_custom").val($(this).val());
        });
    });
</script>

用户名_自定义 ID:

<input id="username_custom" name="custom" value="
<?php 
if(isset($_POST['getusername'])) {

$getusername = $_POST['getusername']; 
echo "".$getusername."";

}
if(empty($_POST['username'])) {

    echo "".$row['username']."";

}
?>
">

用户名_选择 ID:

<select id="username_select" name="getusername">
<?php
    $username = $_SESSION['username'];

    $result = mysql_query("SELECT username FROM account WHERE websiteusername='".$username."'");

while($row = mysql_fetch_array($result)) {

    echo "<option value='".$row['username']."'>".$row['username']."</option>";

}
?>
</select>
4

3 回答 3

2

在输入中显示选择的选定值

$("#YourInputId").val($("#username_custom").val());

设置选择的第一个选项文本

$("#YourInputId").val($("#username_custom option:eq(0)").text());

在选择更改时更改文本框值

$(document).ready(function() { 
    $("#username_select").change(function() { 
        $("#username_custom").val($(this).val());
        $("#YourInputId").val($("#username_custom").val());
    });
});
于 2013-03-28T05:48:25.180 回答
1

在这一行

echo "<option value='".$row['username']."'>".$row['username']."</option>";

您可以将 SELECTED 添加到要选择的选项中。您可以在 while 循环中使用变量来找出您所在的项目并选择该项目;

例如。

$ctr = 0;

while($row = mysql_fetch_array($result)) {

   echo "<option value='".$row['username']."'" . ( $ctr == 1 ? "selected" : "" ) . ">".$row['username']."</option>";
   $ctr++
}

希望这可以帮助。干杯

于 2013-03-28T05:54:03.163 回答
1

在这种情况下,您还可以调用下拉的更改事件。

$("#username_select").change();
于 2013-03-28T05:59:10.533 回答