更新输入值到元素只有JS

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

Update input values into elements only JS

问题

我已创建了一个索引文件,以便在此处输入的信息添加到创建的元素中。这是用于评论部分的。

index.html文件在这里,包括CSS和JavaScript。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body>
    <div class="msg">
        <div class="items"></div>
        <div class="input">
            <input type="text" class="name" placeholder="Name">
            <input type="text" class="message" placeholder="Message">
            <button id="button">Submit</button>
            <button type="reset">Reset</button>
        </div>
    </div>
</body>
</html>
html, body {
    padding: 0;
    margin: 0;
}

.msg {
    padding: 2em;
    margin: 2em;
    border-radius: 2vh;
    height: 70vh;
    display: flex;
    align-items: center;
    justify-content: left;
    flex-direction: column;
    background-color: #1e90ff;
}

.items {
    height: 65vh;
    overflow: scroll;
    color: white;
    width: 100%;
    overflow-x: hidden;
    margin: 10px;
}

input {
    padding: 10px;
    border: none;
    border-radius: 8px;
    outline: none;
    font-size: 1em;
}

#button {
    padding: 10px 20px;
    border-radius: 8px;
    border: none;
    font-size: 1em;
}

.button {
    padding: 10px 20px;
    border-radius: 8px;
    border: none;
    font-size: 1em;
}

.message-item {
    background-color: black;
    padding: 1em;
    border-radius: 8px;
    margin: 3px;
}
let name = document.querySelector('.name').value;
let message = document.querySelector('.message').value;
let btn = document.getElementById('button');
let div = document.querySelector('.items')

btn.addEventListener('click', () => {
    let item = document.createElement('div')
    let inner = `
        <h3>${name}</h3>
        <p>${message}</p>
    `
    item.className = "message-item"
    item.innerHTML = inner
    div.append(item)
});

所以,我期望它会附加具有不同值的元素。例如,一旦我输入name为“harry”和message为“this is the message”,然后重置并输入另一个namemessage,新创建的元素应该显示新输入的namemessage

英文:

I have created an index file so that the information entered here is added to the created element
this is for a review section
the index.html file is here, and includes the CSS and js

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    let name = document.querySelector(&#39;.name&#39;).value;
    let message = document.querySelector(&#39;.message&#39;).value;
    let btn = document.getElementById(&#39;button&#39;);
    let div = document.querySelector(&#39;.items&#39;)

    btn.addEventListener(&#39;click&#39;, ()=&gt;{
        let item = document.createElement(&#39;div&#39;)
        let inner = `
                &lt;h3&gt;${name}&lt;/h3&gt;
                &lt;p&gt;${message}&lt;/p&gt;
                `
        item.className = &quot;message-item&quot;        
        item.innerHTML = inner        
        div.append(item)
    });

<!-- language: lang-css -->

 html, body{
            padding: 0;
            margin: 0;
        }
        .msg{
            padding: 2em;
            margin: 2em;
            border-radius: 2vh;
            height: 70vh;
            display: flex;
            align-items: center;
            justify-content: left;
            flex-direction: column;
            background-color: #1e90ff;
        }
        .items{
            height: 65vh;
            overflow: scroll;
            color: white;
            width: 100%;
            overflow-x: hidden;
            margin: 10px;
        }
        input{
            padding: 10px;
            border: none;
            border-radius: 8px;
            outline: none;
            font-size: 1em;
        }
        #button{
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            font-size: 1em;
        }
        .button{
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            font-size: 1em;
        }
        .message-item{
            background-color: black;
            padding: 1em;
            border-radius: 8px;
            margin: 3px;
        }

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;&lt;/title&gt;

&lt;/head&gt;
&lt;body&gt;
    &lt;div class=&quot;msg&quot;&gt;
        &lt;div class=&quot;items&quot;&gt;&lt;/div&gt;
        &lt;div class=&quot;input&quot;&gt;
                &lt;input type=&quot;text&quot; class=&quot;name&quot; placeholder=&quot;Name&quot;&gt;
                &lt;input type=&quot;text&quot; class=&quot;message&quot; placeholder=&quot;Message&quot;&gt;
                &lt;button id=&quot;button&quot;&gt;Submit&lt;/button&gt;
                &lt;button type=&quot;reset&quot;&gt;Reset&lt;/button&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/body&gt;

&lt;/html&gt;

<!-- end snippet -->

So I am expecting it to append the elements which have different values
example once i enter the **name **"harry" and **message **as "this is the message"
and then i reset and enter another **name **and **message **then the newly created element should display the newly entered **name **and message

答案1

得分: 0

Your name variable should be a pointer to the element, not the value.

Also, you should clear the input after adding.

英文:

Your name variable should be a pointer to the element, not the value.

Also, you should clear the input after adding.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const
  name = document.querySelector(&#39;.name&#39;),
  message = document.querySelector(&#39;.message&#39;),
  btn = document.getElementById(&#39;button&#39;),
  div = document.querySelector(&#39;.items&#39;);

const handleAdd = (e) =&gt; {
  div.insertAdjacentHTML(&#39;beforeend&#39;, `
    &lt;div class=&quot;message-item&quot;&gt;
      &lt;h3&gt;${name.value}&lt;/h3&gt;
      &lt;p&gt;${message.value}&lt;/p&gt;
    &lt;/div&gt;
  `);
  name.value = &#39;&#39;;    // Clear name
  message.value = &#39;&#39;; // Clear message
};

btn.addEventListener(&#39;click&#39;, handleAdd);

<!-- language: lang-css -->

html,
body {
  padding: 0;
  margin: 0;
}

.msg {
  padding: 2em;
  margin: 2em;
  border-radius: 2vh;
  height: 70vh;
  display: flex;
  align-items: center;
  justify-content: left;
  flex-direction: column;
  background-color: #1e90ff;
}

.items {
  height: 65vh;
  overflow: scroll;
  color: white;
  width: 100%;
  overflow-x: hidden;
  margin: 10px;
}

input {
  padding: 10px;
  border: none;
  border-radius: 8px;
  outline: none;
  font-size: 1em;
}

#button {
  padding: 10px 20px;
  border-radius: 8px;
  border: none;
  font-size: 1em;
}

.button {
  padding: 10px 20px;
  border-radius: 8px;
  border: none;
  font-size: 1em;
}

.message-item {
  background-color: black;
  padding: 1em;
  border-radius: 8px;
  margin: 3px;
}

<!-- language: lang-html -->

&lt;div class=&quot;msg&quot;&gt;
  &lt;div class=&quot;items&quot;&gt;&lt;/div&gt;
  &lt;div class=&quot;input&quot;&gt;
    &lt;input type=&quot;text&quot; class=&quot;name&quot; placeholder=&quot;Name&quot;&gt;
    &lt;input type=&quot;text&quot; class=&quot;message&quot; placeholder=&quot;Message&quot;&gt;
    &lt;button id=&quot;button&quot;&gt;Submit&lt;/button&gt;
    &lt;button type=&quot;reset&quot;&gt;Reset&lt;/button&gt;
  &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

A better approach

A better example would be to use a form. This way you can take advantage of built-in form validation, submission, and resetting.

For example, you can call elements by their name and you have the added bonus of <kbd>Enter</kbd> key support.

  1. Enter a name
  2. Press <kbd>Tab</kbd>
  3. Enter a message
  4. Press <kbd>Enter</kbd>
    1. The item is added
    2. The form is cleared
    3. Focus is sent to the name

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const handleAdd = (e) =&gt; {
  e.preventDefault(); // Prevent page from navigating
  const
    form = e.target,
    formElements = form.elements,
    parent = form.closest(&#39;.msg&#39;),
    items = parent.querySelector(&#39;.items&#39;);
  items.insertAdjacentHTML(&#39;beforeend&#39;, `
    &lt;div class=&quot;message-item&quot;&gt;
      &lt;h3&gt;${formElements.name.value}&lt;/h3&gt;
      &lt;p&gt;${formElements.message.value}&lt;/p&gt;
    &lt;/div&gt;
  `);
  formElements.name.value = &#39;&#39;;    // Clear name
  formElements.message.value = &#39;&#39;; // Clear message
  formElements.name.focus();
};

document.forms.namedItem(&#39;new-msg&#39;)
  .addEventListener(&#39;submit&#39;, handleAdd);

<!-- language: lang-css -->

html,
body {
  padding: 0;
  margin: 0;
}

.msg {
  padding: 2em;
  margin: 2em;
  border-radius: 2vh;
  height: 70vh;
  display: flex;
  align-items: center;
  justify-content: left;
  flex-direction: column;
  background-color: #1e90ff;
}

.items {
  height: 65vh;
  overflow: scroll;
  color: white;
  width: 100%;
  overflow-x: hidden;
  margin: 10px;
}

input {
  padding: 10px;
  border: none;
  border-radius: 8px;
  outline: none;
  font-size: 1em;
}

.form-btn {
  padding: 10px 20px;
  border-radius: 8px;
  border: none;
  font-size: 1em;
}

.message-item {
  background-color: black;
  padding: 1em;
  border-radius: 8px;
  margin: 3px;
}

<!-- language: lang-html -->

&lt;div class=&quot;msg&quot;&gt;
  &lt;div class=&quot;items&quot;&gt;&lt;/div&gt;
  &lt;form id=&quot;new-msg&quot; autocomplete=&quot;off&quot;&gt;
    &lt;input type=&quot;text&quot; name=&quot;name&quot; placeholder=&quot;Name&quot; required&gt;
    &lt;input type=&quot;text&quot; name=&quot;message&quot; placeholder=&quot;Message&quot;&gt;
    &lt;button type=&quot;submit&quot; class=&quot;form-btn&quot;&gt;Submit&lt;/button&gt;
    &lt;button type=&quot;reset&quot; class=&quot;form-btn&quot;&gt;Reset&lt;/button&gt;
  &lt;/form&gt;
&lt;/div&gt;

<!-- end snippet -->


LocalStorage

Here is an example of local storage. The main idea here is how to store and restore the state of the messages.

const MESSAGES_KEY = &quot;messages&quot;;

const main = () =&gt; {
  // Restore all messages
  const messageContainer = document.querySelector(&quot;.items&quot;);
  __retrieveAllMessages().forEach((message) =&gt; {
    insertMessage(message, messageContainer);
  });
  // Add event listener
  document.forms.namedItem(&quot;new-msg&quot;).addEventListener(&quot;submit&quot;, handleAdd);
};

const saveMessage = (message) =&gt; {
  __saveAllMessages(__retrieveAllMessages().concat(message));
};

const insertMessage = (message, container) =&gt; {
  container.insertAdjacentHTML(&quot;beforeend&quot;, messageToHtml(message));
};

const messageToHtml = ({ name, message }) =&gt; `
  &lt;div class=&quot;message-item&quot;&gt;
    &lt;h3&gt;${name}&lt;/h3&gt;
    &lt;p&gt;${message}&lt;/p&gt;
  &lt;/div&gt;
`;

const handleAdd = (e) =&gt; {
  e.preventDefault(); // Prevent page from navigating
  const form = e.target,
    message = {
      name: form.elements.name.value,
      message: form.elements.message.value,
    };
  saveMessage(message);
  insertMessage(message, form.closest(&quot;.msg&quot;).querySelector(&quot;.items&quot;));
  form.elements.name.value = &quot;&quot;; // Clear name
  form.elements.message.value = &quot;&quot;; // Clear message
  form.elements.name.focus();
};

const __retrieveAllMessages = () =&gt; {
  return JSON.parse(localStorage.getItem(MESSAGES_KEY) ?? &quot;[]&quot;);
};

const __saveAllMessages = (messages = []) =&gt; {
  return localStorage.setItem(MESSAGES_KEY, JSON.stringify(messages));
};

main();

答案2

得分: 0

你需要在每次点击提交按钮时获取输入的值,而不仅仅是在页面加载时获取一次,并且在按下重置按钮时需要清除输入的值。

let btn = document.getElementById('button');
let reset = document.getElementById('reset');
let div = document.querySelector('.items');

btn.addEventListener('click', () => {
  let name = document.querySelector('.name').value;
  let message = document.querySelector('.message').value;
  let item = document.createElement('div');
  let inner = `
    <h3>${name}</h3>
    <p>${message}</p>
  `;
  item.className = "message-item";
  item.innerHTML = inner;
  div.append(item);
});

reset.addEventListener('click', () => {
  document.querySelector('.name').value = '';
  document.querySelector('.message').value = '';
});

CSS和HTML部分不需要翻译。

英文:

You need to get the values of your input on every button submit button press, not just once on page load, and also you need to clear your inputs when you press the reset button

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let btn = document.getElementById(&#39;button&#39;);
let reset = document.getElementById(&#39;reset&#39;);
let div = document.querySelector(&#39;.items&#39;)
btn.addEventListener(&#39;click&#39;, () =&gt; {
let name = document.querySelector(&#39;.name&#39;).value;
let message = document.querySelector(&#39;.message&#39;).value;
let item = document.createElement(&#39;div&#39;)
let inner = `
&lt;h3&gt;${name}&lt;/h3&gt;
&lt;p&gt;${message}&lt;/p&gt;
`
item.className = &quot;message-item&quot;
item.innerHTML = inner;
div.append(item)
});
reset.addEventListener(&#39;click&#39;, () =&gt; {
let name = document.querySelector(&#39;.name&#39;).value = &#39;&#39;;
let message = document.querySelector(&#39;.message&#39;).value = &#39;&#39;;
});

<!-- language: lang-css -->

html, body{
padding: 0;
margin: 0;
}
.msg{
padding: 2em;
margin: 2em;
border-radius: 2vh;
height: 70vh;
display: flex;
align-items: center;
justify-content: left;
flex-direction: column;
background-color: #1e90ff;
color: white;
}
.items{
height: 65vh;
overflow: scroll;
color: white;
width: 100%;
overflow-x: hidden;
margin: 10px;
}
input{
padding: 10px;
border: none;
border-radius: 8px;
outline: none;
font-size: 1em;
}
#button{
padding: 10px 20px;
border-radius: 8px;
border: none;
font-size: 1em;
}
.button{
padding: 10px 20px;
border-radius: 8px;
border: none;
font-size: 1em;
}
.message-item{
background-color: black;
padding: 1em;
border-radius: 8px;
margin: 3px;
}

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;title&gt;&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class=&quot;msg&quot;&gt;
&lt;div class=&quot;items&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;input&quot;&gt;
&lt;input type=&quot;text&quot; class=&quot;name&quot; placeholder=&quot;Name&quot;&gt;
&lt;input type=&quot;text&quot; class=&quot;message&quot; placeholder=&quot;Message&quot;&gt;
&lt;button id=&quot;button&quot;&gt;Submit&lt;/button&gt;
&lt;button id=&quot;reset&quot;&gt;Reset&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

答案3

得分: -1

你可以从输入中获取值,但它们在填充之前就是字符串值,不会在输入更改时动态更新。

我将这些代码移到了你的函数内部,这样每次点击按钮时都会获取到最新的数据。

<!-- 开始代码段: js 隐藏: false 控制台: true Babel: false -->

<!-- 语言: lang-js -->
let btn = document.getElementById('button');
btn.addEventListener('click', () => {
    let name = document.querySelector('.name').value;
    let message = document.querySelector('.message').value;
    let div = document.querySelector('.items')

    let item = document.createElement('div')
    let inner = `
            <h3>${name}</h3>
            <p>${message}</p>
            `
    item.className = "message-item"
    item.innerHTML = inner
    div.append(item)
});

<!-- 语言: lang-css -->
html, body{
    padding: 0;
    margin: 0;
}
.msg{
    padding: 2em;
    margin: 2em;
    border-radius: 2vh;
    height: 70vh;
    display: flex;
    align-items: center;
    justify-content: left;
    flex-direction: column;
    background-color: #1e90ff;
}
.items{
    height: 65vh;
    overflow: scroll;
    color: white;
    width: 100%;
    overflow-x: hidden;
    margin: 10px;
}
input{
    padding: 10px;
    border: none;
    border-radius: 8px;
    outline: none;
    font-size: 1em;
}
#button{
    padding: 10px 20px;
    border-radius: 8px;
    border: none;
    font-size: 1em;
}
.button{
    padding: 10px 20px;
    border-radius: 8px;
    border: none;
    font-size: 1em;
}
.message-item{
    background-color: black;
    padding: 1em;
    border-radius: 8px;
    margin: 3px;
}

<!-- 语言: lang-html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body>
    <div class="msg">
        <div class="items"></div>
        <div class="input">
                <input type="text" class="name" placeholder="Name">
                <input type="text" class="message" placeholder="Message">
                <button id="button">Submit</button>
                <button type="reset">Reset</button>
        </div>
    </div>
</body>
</html>

<!-- 结束代码段 -->
英文:

You get the values from your inputs before they are filled. They are just string values and do not update dynamically when the input changes.

I moved these lines to inside your function so that you get the most recent data every time you click the button.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let btn = document.getElementById(&#39;button&#39;);
btn.addEventListener(&#39;click&#39;, ()=&gt;{
let name = document.querySelector(&#39;.name&#39;).value;
let message = document.querySelector(&#39;.message&#39;).value;
let div = document.querySelector(&#39;.items&#39;)
let item = document.createElement(&#39;div&#39;)
let inner = `
&lt;h3&gt;${name}&lt;/h3&gt;
&lt;p&gt;${message}&lt;/p&gt;
`
item.className = &quot;message-item&quot;        
item.innerHTML = inner        
div.append(item)
});

<!-- language: lang-css -->

html, body{
padding: 0;
margin: 0;
}
.msg{
padding: 2em;
margin: 2em;
border-radius: 2vh;
height: 70vh;
display: flex;
align-items: center;
justify-content: left;
flex-direction: column;
background-color: #1e90ff;
}
.items{
height: 65vh;
overflow: scroll;
color: white;
width: 100%;
overflow-x: hidden;
margin: 10px;
}
input{
padding: 10px;
border: none;
border-radius: 8px;
outline: none;
font-size: 1em;
}
#button{
padding: 10px 20px;
border-radius: 8px;
border: none;
font-size: 1em;
}
.button{
padding: 10px 20px;
border-radius: 8px;
border: none;
font-size: 1em;
}
.message-item{
background-color: black;
padding: 1em;
border-radius: 8px;
margin: 3px;
}

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;&lt;/title&gt;

&lt;/head&gt;
&lt;body&gt;
    &lt;div class=&quot;msg&quot;&gt;
        &lt;div class=&quot;items&quot;&gt;&lt;/div&gt;
        &lt;div class=&quot;input&quot;&gt;
                &lt;input type=&quot;text&quot; class=&quot;name&quot; placeholder=&quot;Name&quot;&gt;
                &lt;input type=&quot;text&quot; class=&quot;message&quot; placeholder=&quot;Message&quot;&gt;
                &lt;button id=&quot;button&quot;&gt;Submit&lt;/button&gt;
                &lt;button type=&quot;reset&quot;&gt;Reset&lt;/button&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/body&gt;

&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月1日 22:09:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382811.html
匿名

发表评论

匿名网友

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

确定