JS元素从文本区域检索值时返回’null’。

huangapple go评论72阅读模式
英文:

JS element returns 'null' when retrieving value from textarea

问题

关于我的项目,我正在以异步方式提交一个“推文”表单,但我在检索文本区域的值以传递到我的函数并更新用户界面时遇到了问题。推文/帖子的值都保存在我的模型中(包括推文),并且其他每个字段(用户名、用户个人资料图片、推文图片)都正常显示,但只有文本区域引起了问题,根本不显示。以下是相关的代码供参考。

index.html的部分代码

<div class="post-section">
    <form id="tweet-form" method="post">
        <div class="post-section-row">
            <a class="creator" href="{% url 'change_profile' %}"> 
                <img src="{{ user_profile.profile_picture.url }}" class="profile-pic small-post-section">
            </a>
            <!-- 无法从这一行检索值 -->
            <textarea id="post-content" name="tweet" placeholder="What's Happening?" oninput="autoExpand(this); checkCharacterCount(this)"></textarea>
        </div>

        <!-- 用于显示推文图片预览和删除功能的部分 -->
        <div id="tweet-picture-preview" style="display: none;"></div>

        <div class="post-section-row">
            <div class="error-message"></div>
            <div class="tweet-actions">
                <label for="picture" title="Upload Picture">
                    <span class="material-symbols-outlined">photo_library</span>
                    <span class="tooltiptext">Upload Picture</span>
                    <input type="file" id="picture" name="tweet-picture" class="file-input" accept="image/jpeg, image/png, image/gif, image/jpg" onchange="previewTweetImage(event)">
                </label>                        
                <input type="submit" id="post-button" value="Post">
            </div>
        </div>
    </form>
</div>

JS文件(在DOMContentLoaded监听器内的代码)

const tweetForm = document.querySelector("#tweet-form");
tweetForm.addEventListener('submit', function(event) {
  event.preventDefault();

  const csrftoken = getCookie('csrftoken');
  const formData = new FormData(tweetForm);
  fetch("/post_tweet/", {
    method: "POST",
    body: formData,
    headers: {
      'X-CSRFToken': csrftoken,
    },
  })
  .then(response => response.json())
  .then(data => {
    console.log(data.message);

    // 这里返回 'null'
    const tweetInput = document.getElementById("post-content");
    const tweet = tweetInput.value;

    // ...

    addPostToPage(tweet, tweetImage, username);
  })
  .catch(error => {
    console.log(error);
  }); 
});

我尝试了更改tweetInputquerySelector("#post-content")和上面示例中的getElementById,但没有任何变化。将.value替换为.textContent也是一样,但仍然无法检索相关的值。

如果需要其他文件以供参考和清晰性,请告诉我。提前谢谢!

英文:

For my project, I'm submitting a "tweet" form asynchronously, but I'm having trouble retrieving the textarea value to pass into my function and update the UI. The values from the tweet/post are saving to my models (including the tweet) and every other field in (username, user profile picture, tweet image) are displaying properly, but its just the textarea that's causing me problems and not displaying at all. Here is the relevant code for reference.

Section of index.html

            &lt;form id=&quot;tweet-form&quot; method=&quot;post&quot;&gt;
                &lt;div class=&quot;post-section-row&quot;&gt;
                    &lt;a class=&quot;creator&quot; href=&quot;{% url &#39;change_profile&#39; %}&quot;&gt; 
                        &lt;img src=&quot;{{ user_profile.profile_picture.url }}&quot; class=&quot;profile-pic small-post-section&quot; &gt;
                    &lt;/a&gt;
                    &lt;!-- Cannot retrieve value from this line --&gt;
                    &lt;textarea id=&quot;post-content&quot; name=&quot;tweet&quot; placeholder=&quot;What&#39;s Happening?&quot; oninput=&quot;autoExpand(this); checkCharacterCount(this)&quot;&gt;&lt;/textarea&gt;

                &lt;/div&gt;

                &lt;!-- To display tweet image preview and delete functionality --&gt;
                &lt;div id=&quot;tweet-picture-preview&quot; style=&quot;display: none;&quot;&gt;&lt;/div&gt;

                &lt;div class=&quot;post-section-row&quot;&gt;
                    &lt;div class=&quot;error-message&quot;&gt;&lt;/div&gt;
                    &lt;div class=&quot;tweet-actions&quot;&gt;
                        &lt;label for=&quot;picture&quot; title=&quot;Upload Picture&quot;&gt;
                            &lt;span class=&quot;material-symbols-outlined&quot;&gt;photo_library&lt;/span&gt;
                            &lt;span class=&quot;tooltiptext&quot;&gt;Upload Picture&lt;/span&gt;
                            &lt;input type=&quot;file&quot; id=&quot;picture&quot; name=&quot;tweet-picture&quot; class=&quot;file-input&quot; accept=&quot;image/jpeg, image/png, image/gif, image/jpg&quot; onchange=&quot;previewTweetImage(event)&quot;&gt;
                        &lt;/label&gt;                        
                        &lt;input type=&quot;submit&quot; id=&quot;post-button&quot; value=&quot;Post&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/form&gt;

JS file (code within DOMContentLoaded listener)

    tweetForm.addEventListener(&#39;submit&#39;, function(event) {
      event.preventDefault();
  
      const csrftoken = getCookie(&#39;csrftoken&#39;);
      const formData = new FormData(tweetForm);
      fetch(&quot;/post_tweet/&quot;, {
        method: &quot;POST&quot;,
        body: formData,
        headers: {
          &#39;X-CSRFToken&#39;: csrftoken,
        },
      })
      .then(response =&gt; response.json())
      .then(data =&gt; {
        console.log(data.message);

        // This returns &#39;null&#39;
        const tweetInput = document.getElementById(&quot;post-content&quot;);
        const tweet = tweetInput.value;

        // ...

        addPostToPage(tweet, tweetImage, username);
      })
      .catch(error =&gt; {
        console.log(error);
      }); 

I've tried changing the tweetInput from querySelector("#post-content); and getElementById as seen above, and nothing changes. Same with replacing .value with .TextContent, but it's still not able to retrieve the associated value.

Let me know if you require any additional files for reference and clarity. Thank you in advance!

答案1

得分: 0

尝试简化这段代码。首先将文本区域的值存入一个变量,然后在从服务器获得响应后尝试使用它。
检查下面的代码。它是有效的。只需稍后进行服务器请求。

const tweetForm = document.getElementById('tweet-form');
tweetForm.addEventListener('submit', function (event) {
    event.preventDefault();
    const tweetInput = document.getElementById("post-content");
    const tweet = tweetInput.value;
    console.log(tweet);

    // 在此处添加发送请求到服务器的其余代码
});
英文:

Try to simplify this code. You have to first take the textarea value into a variable and then try to use it after getting a response from the server.
Check the below code. It is working. Just do the server request later.

const tweetForm = document.getElementById(&#39;tweet-form&#39;);
tweetForm.addEventListener(&#39;submit&#39;, function (event) {
    event.preventDefault();
    const tweetInput = document.getElementById(&quot;post-content&quot;);
    const tweet = tweetInput.value;
    console.log(tweet);

    // your rest of the code to send requests on the server
});

huangapple
  • 本文由 发表于 2023年6月13日 02:20:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76459321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定