如何在文本字段中显示所有选定的选项
how do I show all the selected options in the text field
如何让我的 javascript 显示在文本字段中选择的多个 我正计划添加更多的,所以我不想制作一个疯狂的长数组
function myFunction() {
var skilllist = document.getElementById("skilllist");
console.log(skilllist.selectedIndex);
document.getElementById("skillfield").value = skilllist.options[skilllist.selectedIndex].text;
}
<form>
Select your favorite browser:
<select name="skillist[]" id="skilllist" multiple>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
<option value="Javascript">Javascript</option>
<option value="PHP">PHP</option>
<option value="Laravel">Laravel</option>
<option value="Wordpress">wordpress</option>
</select>
<p>jouw skills zijn: <input type="text" id="skillfield" size="50"></p>
</form>
</div>
我建议将 blur
事件的事件处理程序添加到 select 元素。
通过这种方法,您可以 select 一个或多个列表项并动态呈现它们的文本内容。
document.getElementById("skilllist").addEventListener('blur', function(e){
var options = e.target.options,
selected_content = "";
for (var i = 0; i < options.length; i++) {
if (options[i].selected) selected_content += options[i].textContent + ", ";
}
document.getElementById("skillfield").value = selected_content;
});
https://jsfiddle.net/zLyw7vhd/
For mobile devices : try to replace event name 'blur'
to 'focusout'
(or 'change'
) in addEventListener
function
如何让我的 javascript 显示在文本字段中选择的多个 我正计划添加更多的,所以我不想制作一个疯狂的长数组
function myFunction() {
var skilllist = document.getElementById("skilllist");
console.log(skilllist.selectedIndex);
document.getElementById("skillfield").value = skilllist.options[skilllist.selectedIndex].text;
}
<form>
Select your favorite browser:
<select name="skillist[]" id="skilllist" multiple>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
<option value="Javascript">Javascript</option>
<option value="PHP">PHP</option>
<option value="Laravel">Laravel</option>
<option value="Wordpress">wordpress</option>
</select>
<p>jouw skills zijn: <input type="text" id="skillfield" size="50"></p>
</form>
</div>
我建议将 blur
事件的事件处理程序添加到 select 元素。
通过这种方法,您可以 select 一个或多个列表项并动态呈现它们的文本内容。
document.getElementById("skilllist").addEventListener('blur', function(e){
var options = e.target.options,
selected_content = "";
for (var i = 0; i < options.length; i++) {
if (options[i].selected) selected_content += options[i].textContent + ", ";
}
document.getElementById("skillfield").value = selected_content;
});
https://jsfiddle.net/zLyw7vhd/
For mobile devices : try to replace event name
'blur'
to'focusout'
(or'change'
) inaddEventListener
function