如何从输入表单中获取值,并在我的javascript函数之一中使用它

How to get values from input form, and use it in one of my javascript functions

本文关键字:函数 javascript 我的 输入 表单 获取      更新时间:2023-09-26

下面是我的代码,我希望能够使用任何用户输入作为我的showColor函数的值。我用的是文档。getElementsByName,但我得到了一些错误类型错误。有人能帮忙吗?谢谢!

<input type="text" name="color" value="Input Your Fav Color">
<button type="button" onClick="showColor('red')">Show Color</button>

我猜是因为你在做这个

document.getElementsByName('color').value

你应该这样做

document.getElementsByName('test')[0].value

因为getElementsByName返回一个集合,或者给元素一个id而使用getElementById

您将需要为目标input分配一个id,以便您可以轻松地通过javascript检索其值。

<input id="userColor" type="text" name="color" value="Input Your Fav Color" >

然后可以像这样检索值:

var usercolor = document.getElementById('userColor').value;

或者用你的例子

<button type="button" onClick="showColor(document.getElementById('userColor').value)">Show Color</button>

Use DOM:

<button type="button" onClick="showColor(document.getElementsByName('color')[0].value)">Show Color</button>

如果页面上有更多名称为color的元素,则会出现问题,但我假设您没有。

您实际上需要使用。getelementbyid ("color")并且输入为

<input type="text" name="color" id="color" value="Input Your Fav Color">