【问题标题】:I'm having trouble getting an array of inputs from a single form field我无法从单个表单字段中获取输入数组
【发布时间】:2019-09-02 15:32:33
【问题描述】:

我正在尝试从输入字段中获取字符串数组,并在每次 keyup(enter) 时清除该字段(这是一个练习,我将在以下位置截取完整的挑战:1. 单个消息

创建一个消息输入,您可以在其中键入任何消息。 当您按 Enter 时,消息应出现在“消息”框中,并且输入应清除

  1. 多条消息

创建新消息时,不要替换“消息”框中的消息,而是将新消息添加到最后一条的底部)。

我得到 main.js:9 Uncaught TypeError: Cannot read property 'textContent' of null,我已经尝试过 value 并得到同样的东西,我已经尝试通过定位 id 并获得 undefined 或 null。

我是 Jquery 的新手,我已经阅读了文档,但是我尝试了许多不同的方法,但似乎没有任何效果。

这是我的 HTML

    <body>
        <div class="container-fluid">
            <div class="container">
            <form id="msg-input">
                <input type="text" placeholder="sample text" id="input-test" action="submit">
            </form> 
            </div>
            <div class="alert alert-info" id="alert-primary" role="alert">
                msg goes here
            </div>

这是我的 JQuery,我已经尝试了所有我能想到的方法,包括 - 添加 .value() .textcontent() 等 我只需要在提交输入框和框重置时将输入保存到 var 数组中

$('#alert-primary').hide()// hides first msg initially

$('#msg-input').on('submit', function(e) { //on submit prevents refresh
    e.preventDefault(); 

$('#msg-input').each(function() { //loops through each ipnut 
    var messages = []; // initializes var messages
        messages.push((document.getElementById("#input-test").textContent()));// pushes string to messages array
$('#msg-input').reset();     //resets input field
    });
 console.log(messages); //logs messages
})

我想要一个消息文本框(对讲机、fb 等)。但对于 现在希望能够存储输入。我会生成 消息 之后。这里的目标是使用 javascript。

【问题讨论】:

  • $('#msg-input').each() 没有意义,因为 id 应该是唯一的。
  • 对不起,我的意思是使用 jquery。
  • @taplar 它的一个输入框
  • 每次输入后我需要清除输入并保存到数组,这样我就可以从我的 jquery 在 html 中生成一个消息框

标签: jquery arrays input


【解决方案1】:

试试这样的:

var messages = []; // Take care to not clean your array in "each" execution

$('#msg-input input').each(function() { // Get each input inside forms
    messages.push(this.value); // Get value of this (input)
});

【讨论】:

  • 我最终使用了这个:
  • $('#msg-input').on('submit', function (e) { console.log(e); e.preventDefault(); //on submit 防止刷新 $( '#alert.primary').show('slow'); messages.push($('#input-test').val()); console.log(messages); $('#input-test') .val(''); });
  • @taplar 谢谢你的帮助!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 2017-09-27
  • 2018-07-24
  • 2021-09-30
  • 1970-01-01
相关资源
最近更新 更多