【问题标题】:for each option create new elements and remove other if they exists为每个选项创建新元素并删除其他元素(如果存在)
【发布时间】:2017-08-12 14:23:46
【问题描述】:

onchange 如何删除和添加新元素?我希望为每个选项创建新元素并删除其他元素(如果存在),https://codepen.io/Datik/pen/Bddmrv

每个选项都有自己的需要在表单上显示的元素“列表”

例如: 选项标准将仅显示输入类型='文本'

选项 VIP 将显示输入并选择

现在,它只是在我选择选项时创建新元素,尝试检查 childNodes.length,没有帮助

document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[name="productType"]').onchange=changeEventHandler;},false);


function changeEventHandler(event) {
  var getSelect = document.getElementById('product');
  var newInput = document.createElement('input');
  var newSelect = document.createElement('select');
  newInput.setAttribute('type','text');
  newInput.setAttribute('placeholder','title');
    if(event.target.value=='Standard'){
      // if(getSelect.childNodes.length>0){
      //   getSelect.removeChild(newInput);
      // }
     getSelect.parentNode.appendChild(newInput);
    }
    else if(event.target.value=='VIP'){
     getSelect.parentNode.appendChild(newInput);
     getSelect.parentNode.appendChild(newSelect);
    }
    else{
    getSelect.removeChild(newInput);//tried to delete 1 input if choose 1st option
    }
}

【问题讨论】:

    标签: javascript dom


    【解决方案1】:

    您正在尝试使用以下代码从 getSelect 元素中删除 newInput 元素:

    getSelect.removeChild(newInput);
    

    但您的输入和选择位于同一 dom 级别。试试这个:

    getSelect.parentNode.removeChild(newInput);
    

    您还可以简化您的代码。只需为新字段添加容器,操作起来会更容易。这是工作示例:

    html:

    <div class="container">
    <fieldset>
        <select name="productType" id="product">
            <option> </option>
            <option>Standard</option>
            <option>VIP</option>
        </select>
    </fieldset>
    <div id="fields">
    
    </div>
    

    js:

    document.addEventListener('DOMContentLoaded',function() {
        document.querySelector('select[name="productType"]').onchange=changeEventHandler;},false);
    
    
    function changeEventHandler(event) {
        //add container for product fields
        var fieldsContainer = document.getElementById('fields');
        //clean container
        fieldsContainer.innerHTML = '';
    
        var newInput = document.createElement('input');
        newInput.setAttribute('type','text');
        newInput.setAttribute('placeholder','title');
    
        if(event.target.value=='Standard'){
            fieldsContainer.appendChild(newInput);
        }
        else if(event.target.value=='VIP'){
            var newSelect = document.createElement('select');
            fieldsContainer.appendChild(newInput);
            fieldsContainer.appendChild(newSelect);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多