如果我输入值,Javascript 函数会显示文本

标签 javascript jquery html dom user-input

到目前为止,如果我在输入字段中输入值“20”,则显示消息“谢谢”。

这是我的 HTML 代码:

<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="submit" value="submit">
</form>

这是我的 JS 代码:

$(document).ready(function(){

    var money = 20;

    /* not sure if this is written correctly, but this is supposed to
    check whether the hidden input element value is equal to var money */

    if ($("input[id='nominal']").val() == money )  {

     var h = document.createElement("H1")                // Create a <h1> element
     var t = document.createTextNode("Thank You");     // Create a text node
     h.appendChild(t);                                   // Append the text to <h1>

    };
});

我创建了一个脚本来满足我的需要,但不起作用!怎么了?

My JDFIDDLE LINK

最佳答案

您必须创建一个事件来监听更改,在本例中为changed。你也可以让你的代码更小一些。 ;)

$(function() {
    $("#nominal").change(function() {
        if( $(this).val() == 20 )
            $(this).after("<h1>Thank You</h1>");
    });
});

完整的工作示例,当值再次更改时删除消息并严格检查可以是 seen here .

关于如果我输入值,Javascript 函数会显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38454932/

相关文章:

html - 设置没有填充/边距的 div 宽度

javascript - iFrame 自动刷新不适用于 Chrome,但适用于 IE

javascript - 在 NextJS/React 中加载 Skeleton 实现

javascript - 将特定文本与 Angular 列表中的文本字段交换

javascript - 读取 JSON 并在 HTML 中实现

jQuery ON 错误。使用LIVE时没有错误

javascript - 如何使用 peerJS 点对点连接接收数据?

javascript - 如何使用 jquery 在数据表中添加数据?

javascript - 在列表中添加元素后如何清空输入字段?

javascript - 如果在选择框中选择了相关项目,则打开隐藏的 div