简体   繁体   English

当 select 框更改 JavaScript 中的值时,如何添加和删除消息?

[英]How to add a message and remove it when a select box changes value in JavaScript?

I'm trying to create a message that alerts a customer when a specific value is selected in a Select Box.我正在尝试创建一条消息,当在 Select 框中选择特定值时提醒客户。 My goal is to append this message underneath a description paragraph when option_2 is selected, and remove the message when any other value is selected.我的目标是在选择option_2时在描述段落下方 append 此消息,并在选择任何其他值时删除该消息。

I'm having two problems:我有两个问题:

  1. I'm able to get the message to append in my local development (for some reason I cannot get this to work in JSFiddle), but I can't get it to remove我能够在我的本地开发中收到 append 的消息(由于某种原因,我无法让它在 JSFiddle 中工作),但我无法将其删除
  2. Every time option_2 is selected, another p element gets appended, probably a symptom of problem 1.每次选择option_2时,都会附加另一个p元素,这可能是问题 1 的症状。

Here's a fiddle!这是一个小提琴! Fiddle小提琴

HTML: HTML:

<h2>
  Choose an Option:
</h2>
<select id="test">
  <option value="option_1">Option 1</option>
  <option value="option_2">Option 2</option>
  <option value="option_3">Option 3</option>
</select>

<h3>
  Add Ons:
</h3>
<div class="wc-pao-addon-tone-cap">
  <div class="wc-pao-addon-description">
  <p>
    These are the add ons that you can have:
  </p>
  </div>
  <p>
    <label><input type="checkbox">Add On 1</label>
  </p>
  <p>
    <label><input type="checkbox">Add On 2</label>
  </p>
  <p>
    <label><input type="checkbox">Add On 3</label>
  </p>
</div>

JavaScript JavaScript

function alertMessage() {
  let toneTwo = document.querySelector('#test');
  let toneCap = document.querySelector('.wc-pao-addon-tone-cap');
  let description = document.querySelector('.wc-pao-addon-description');
  let descriptionParagraph = description.firstChild;


  toneTwo.addEventListener('change', () => {
    if (toneTwo.value == "option_2") {

      const newMessage = document.createElement('p');
      newMessage.innerHTML = '<p class="option-two-alert" style="color: red; margin: 10px 0 0;"><i class="fas fa-exclamation-circle"></i> Select Only One Add On When Option 2 Is Selected.</p>';
      descriptionParagraph.appendChild(newMessage);
    } else {
      newMessage.innerHTML = '';
      descriptionParagraph.removeChild(newMessage);
    }
  });
}

window.addEventListener("load", alertMessage);

firstChild returns the first child node as an element node, a text node or a comment node which you probably do not want. firstChild将第一个子节点作为元素节点、文本节点或您可能不想要的注释节点返回。 Try using firstElementChild .尝试使用firstElementChild

Change改变

let descriptionParagraph = description.firstChild;

To

let descriptionParagraph = description.firstElementChild;

To remove the message you can use the following code in else part要删除消息,您可以在其他部分使用以下代码

let m = document.querySelector('.option-two-alert')
if(m) { m.remove() };

Demo:演示:

 function alertMessage() { let toneTwo = document.querySelector('#test'); let toneCap = document.querySelector('.wc-pao-addon-tone-cap'); let description = document.querySelector('.wc-pao-addon-description'); let descriptionParagraph = description.firstElementChild; toneTwo.addEventListener('change', () => { if (toneTwo.value == "option_2") { const newMessage = document.createElement('p'); newMessage.innerHTML = '<p class="option-two-alert" style="color: red; margin: 10px 0 0;"><i class="fas fa-exclamation-circle"></i> Select Only One Add On When Option 2 Is Selected.</p>'; descriptionParagraph.appendChild(newMessage); } else { let m = document.querySelector('.option-two-alert') if(m) { m.remove(); } } }); } window.addEventListener("load", alertMessage);
 <h2> Choose an Option: </h2> <select id="test"> <option value="option_1">Option 1</option> <option value="option_2">Option 2</option> <option value="option_3">Option 3</option> </select> <h3> Add Ons: </h3> <div class="wc-pao-addon-tone-cap"> <div class="wc-pao-addon-description"> <p> These are the add ons that you can have: </p> </div> <p> <label><input type="checkbox">Add On 1</label> </p> <p> <label><input type="checkbox">Add On 2</label> </p> <p> <label><input type="checkbox">Add On 3</label> </p> </div>

The alert is not added on jsfiddle because the first child of the description there is a TextNode. jsfiddle 上没有添加警报,因为描述的第一个孩子有一个 TextNode。 Try using firstElementChild .尝试使用firstElementChild You also have an issue in the event listener, you never remove the alert.您在事件侦听器中也有问题,您永远不会删除警报。 Here's how you can fix it:以下是您可以解决的方法:

function alertMessage() {
  let toneTwo = document.querySelector('#test');
  let toneCap = document.querySelector('.wc-pao-addon-tone-cap');
  let description = document.querySelector('.wc-pao-addon-description');
  let descriptionParagraph = description.firstElementChild;
  let newMessage;

  toneTwo.addEventListener('change', () => {
    if (toneTwo.value == "option_2") {

      newMessage = document.createElement('p');
      newMessage.innerHTML = '<p class="option-two-alert" style="color: red; margin: 10px 0 0;"><i class="fas fa-exclamation-circle"></i> Select Only One Add On When Option 2 Is Selected.</p>';
      descriptionParagraph.appendChild(newMessage);
    } else if (newMessage) {
      descriptionParagraph.removeChild(newMessage);
    }
  });
}

window.addEventListener("load", alertMessage);

You will probably be better off by not inserting a new element in to your DOM every time a user selects "option two", instead you should have the element there all the time and make it visible only when option two is selected:每次用户选择“选项二”时,不要在 DOM 中插入新元素,您可能会更好,相反,您应该始终将元素放在那里,并使其仅在选择选项二时可见:

 window.addEventListener("load", function(){ document.querySelector('#test').addEventListener('change', (ev) => { document.querySelector('.option-two-alert').style.display=ev.target.value=="option_2"?'block':'none'; }) })
 .option-two-alert {display:none} /* initially hidden! */
 <h2> Choose an Option: </h2> <select id="test"> <option value="option_1">Option 1</option> <option value="option_2">Option 2</option> <option value="option_3">Option 3</option> </select> <h3> Add Ons: </h3> <div class="wc-pao-addon-tone-cap"> <div class="wc-pao-addon-description"> <p> These are the add ons that you can have: </p> <p class="option-two-alert" style="color: red; margin: 10px 0 0;"> <i class="fas fa-exclamation-circle"></i> Select Only One Add On When Option 2 Is Selected. </p> </div> <p> <label><input type="checkbox">Add On 1</label> </p> <p> <label><input type="checkbox">Add On 2</label> </p> <p> <label><input type="checkbox">Add On 3</label> </p> </div>

There are some issues in your code, so will brief it, what the expected output you are looking was when you click on the second option you need to have red text wrapped with i and p tag.您的代码中存在一些问题,因此将简要介绍一下,当您单击第二个选项时,您正在寻找的预期 output 是您需要用 i 和 p 标签包裹的红色文本。 That should display below the current p tag **These are the add ons that you can have:**这应该显示在当前 p 标签下方**These are the add ons that you can have:**

Issues to be fixed待修复的问题

  1. let descriptionParagraph = description.firstChild; this will give you the text so you were trying to append to this that wont work.这会给你文本,所以你试图 append 到这个不起作用。
  2. newMessage.innerHTML = '<p class=".... , you can't add like this you need to build the html elements newMessage.innerHTML = '<p class=".... ,你不能像这样添加你需要构建 html 元素
  3. Also you need to have the check description.childNodes[3] && description.removeChild(description.childNodes[3]);您还需要检查description.childNodes[3] && description.removeChild(description.childNodes[3]); , assume if the user directly clicks on option_3 that wont have ap tag so you need to consider that case with this check. , 假设用户直接点击了没有 ap 标签的 option_3,所以你需要通过这个检查来考虑这种情况。

I hope you have got a fair idea我希望你有一个公平的想法

Check the below code.检查下面的代码。

 function alertMessage() { let toneTwo = document.querySelector('#test'); let toneCap = document.querySelector('.wc-pao-addon-tone-cap'); let description = document.querySelector('.wc-pao-addon-description'); toneTwo.addEventListener('change', () => { const newMessage = document.createElement('p'); if (toneTwo.value == "option_2") { let iTag = document.createElement('i'); iTag.className = 'fas fa-exclamation-circle'; let pTag = document.createElement('p'); pTag.style.cssText = "color: red; margin: 10px 0 0"; let pTagText = document.createTextNode("Select Only One Add On When Option 2 Is Selected."); pTag.appendChild(iTag) pTag.appendChild(pTagText) description.appendChild(pTag) } else { newMessage.innerHTML = ''; description.childNodes[3] && description.removeChild(description.childNodes[3]); } }); } window.addEventListener("load", alertMessage);
 <h2> Choose an Option: </h2> <select id="test"> <option value="option_1">Option 1</option> <option value="option_2">Option 2</option> <option value="option_3">Option 3</option> </select> <h3> Add Ons: </h3> <div class="wc-pao-addon-tone-cap"> <div class="wc-pao-addon-description"> <p> These are the add ons that you can have: </p> </div> <p> <label><input type="checkbox">Add On 1</label> </p> <p> <label><input type="checkbox">Add On 2</label> </p> <p> <label><input type="checkbox">Add On 3</label> </p> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 添加/删除选择框jQuery JavaScript - Add/Remove select box jquery javascript 如果其他选择更改,AngularJS将删除并添加选择框选项 - AngularJS remove & add select box option if other selection changes 如果其他选择更改,请删除并添加选择框选项 - remove & add select box option if other selection changes 如何使用javascript添加和删除带有选项的选择框以及带有标签和样式的文本框 - how to add and remove select box with options and text box with label and style using javascript 选择下拉列表值更改时如何调用javascript函数? - How to call javascript function when select dropdown value changes? 如何添加和删除带有选项的选择框? - How to add and remove a select box with options? 当所有 select 框都有一个名称时,我如何从 DOM 添加/删除 select 框,以便在提交时我从活动的 select 框中获取值? - How can I add/remove select boxes from DOM when all select boxes have one name so that upon Submit I get value from active select box? 如何在值更改时向 javascript 对象添加分隔符? - How to add a dividier to an javascript object when a value changes? 选择框时选择Javascript更改值 - Javascript change value when choose on select box 带有更改事件的选择框的javascript - javascript with select box that changes event
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM