-5
A
回答
2
您需要识别表单和输入元素(通过名称或ID)。您需要创建新的select
元素,根据需要为其创建并添加尽可能多的option
元素,最后将其插入现有文本输入元素的位置。
你可以,例如,使用这样的事情:
// ** change 'form' and 'text' to correctly identify the form and text input element **
var inputElement = document.forms['form'].elements['text'];
var selectElement = document.createElement('select');
// get the existing input element's current (or initial) value
var currentValue = inputElement.value || inputElement.getAttribute('value');
// add a list of options to the new select element
// ** change value/text and add/remove options as needed **
var options = [{value: 'option1', text: 'Option 1'},
{value: 'option2', text: 'Option 2'},
{value: 'option3', text: 'Option 3'}];
options.forEach(function (option, i) {
var optionElement = document.createElement('option');
optionElement.appendChild(document.createTextNode(option.text));
optionElement.setAttribute('value', option.value);
selectElement.appendChild(optionElement);
// if the option matches the existing input's value, select it
if (option.value == currentValue) {
selectElement.selectedIndex = i;
}
});
// copy the existing input element's attributes to the new select element
for (var i = 0; i < inputElement.attributes.length; ++ i) {
var attribute = inputElement.attributes[i];
// type and value don't apply, so skip them
// ** you might also want to skip style, or others -- modify as needed **
if (attribute.name != 'type' && attribute.name != 'value') {
selectElement.setAttribute(attribute.name, attribute.value);
}
}
// finally, replace the old input element with the new select element
inputElement.parentElement.replaceChild(selectElement, inputElement);
如果它是连接到它已经没有太多的脚本一个普通的表单元素,这是相当简单的。但是,请注意,如果有任何脚本事件附加到文本元素(焦点,更改,模糊等),那些将不再有效。如果您希望select元素具有相似的脚本事件,则需要重新编写这些事件以应用于它。
新的select
元素可能也会是不同于原始的input
元素的大小/样式;如果您不喜欢默认外观,则可以添加更多代码来更改新元素的样式。
相关问题
- 1. javascript更改选择选项文本
- 2. jquery输入文本更改显示/隐藏选择选项
- 3. 选择选项输入部分文本
- 4. 当选择选项时,Javascript更改输入值
- 5. 更改选择输入选择国家?
- 6. JavaScript - 如何更改基于选择选项中的性别选择的输入文本值
- 7. jQuery切换 - 从选择输入更改为文本输入
- 8. 从选择的选项更新文本输入
- 9. Javascript/jQuery转到下一个输入/选择更改选择值
- 10. 使用javascript更改选择选项
- 11. 更改选项卡选择选项卡时的文本颜色
- 12. 更改选择选项显示的文本,但返回更改选择
- 13. 更改下拉菜单中选择文本,而不更改选项文本
- 14. 更改选择选项选择
- 15. 选择时更改选项
- 16. 更改var选择选项
- 17. 分配选项以通过javascript选择输入
- 18. jQuery获得选择选项ID并更改隐藏输入值
- 19. 动态更改vuejs中的选择输入选项2
- 20. 当我选择选项时更改占位符的输入
- 21. 根据选择选项标签更改输入值
- 22. 允许用户在选择输入中更改输入选择输入
- 23. 使用AJAX根据以前的选择更改表单输入选项
- 24. 如何阻止文本选择不输入文本区域和选择项目
- 25. 克隆和选择框onchange输入文本的更改值
- 26. 选择时如何更改文本输入的CSS?
- 27. 将文本更改为输入,然后再取消选择
- 28. 两个选择选项更改时的一个选择框选项更改
- 29. 检测UIWebView文本选择中的文本选择更改
- 30. 是否可以在角材选择选项中输入文字?
是的,这是可能的。你试过了吗? –
是的;有很多方法可以做到这一点。 SO并不是针对具体的实施问题。去尝试自己实现它,然后回来一个更具体的问题。 – Aeolingamenfel
不,这是不可能的,你不能改变一个元素tagName,但你可以用另一个元素替换它。 – adeneo