在 HTML 中 <select> 如果我已有联系人数据,如何预先填写下拉列表?

问题描述 投票:0回答:1

我需要在下拉菜单上有一个“请选择”,它不应该是可选的,但是添加此选项后,它不会显示我现有的数据,并且默认为“请选择”

使用“请选择”,这是我想要实现的功能 - 它是初始框中显示的文本,而且它也不是下拉列表中的选项 - 但这应该仅在我还没有值时显示联系方式。

<select value="@GENDER@" name="cd_GENDER" ng-init="GENDER = '@GENDER@' || '1'" ng-model="GENDER" id="gender" disabled="">
  <option selected="" hidden="" disabled="" value="">Please Select</option>
<option value="female">Female</option>
<option value="male">Male</option>
 <option value="other">Other</option>
  <option value="prefer to not say">Prefer to not say</option>
</select>

如果我删除

hidden
disabled
selected
- 那么我的“女性”值就会显示,因为它已经存在

<select name="cd_GENDER" ng-init="GENDER = '@GENDER@' || '1'" ng-model="GENDER" id="gender" disabled="">
  <option value="0">Please Select</option>
<option value="female">Female</option>
<option value="male">Male</option>
 <option value="other">Other</option>
  <option value="prefer to not say">Prefer to not say</option>
</select>

我期待着

  1. 新联系人进入表单,他们应该看到“请选择”,然后下拉菜单将有 4 个选项
  2. 返回的联系人访问该表格,他们之前已经提供了“其他” - 应为该联系人显示“其他”

这可能吗?

html forms drop-down-menu html-select
1个回答
0
投票

您的页面上可能有一些选择值的内容。您也许能够快速验证在更改 html 中选项的顺序后是否仍然选择相同的值...

您可能需要参考:Firefox 忽略选项 selected="selected"

所以你可以尝试一下这个,它对你来说会很好

    <select id="gender" name="cd_GENDER" ng-init="GENDER = '@GENDER@' || '1'" ng-model="GENDER">
        <option value="0" hidden>Please Select</option>
        <option value="female">Female</option>
        <option value="male">Male</option>
        <option value="other">Other</option>
        <option value="prefer to not say">Prefer to not say</option>
    </select>
    <script>
        function getSelectionOption(id) {
            let selectionGender = document.getElementById(id);
            let index = selectionGender.options.selectedIndex;
            let valueSelection = selectionGender.options[index].value;
            alert(valueSelection);
        }
        function selection(id, value = 0, disabled = false) {
            let selectionGender = document.getElementById(id);
            let selectedOption = value;
            console.log(selectionGender.options);
            lengthGender = selectionGender.options.length;
            for (let i = 0; i < lengthGender; i++) {
                let optionValue = selectionGender.options[i].value;
                if (optionValue == selectedOption) {
                    console.log(optionValue);
                    selectionGender.options.selectedIndex = i;
                }
            }
            if (disabled) {
                selectionGender.setAttribute('disabled', true);
            } else {
                selectionGender.removeAttribute('disabled');
            }
        }
        selection('gender');
        // selection('gender','other',true);
    </script>
© www.soinside.com 2019 - 2024. All rights reserved.