首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Vanilla JS中将输入框替换为下拉框

如何在Vanilla JS中将输入框替换为下拉框
EN

Stack Overflow用户
提问于 2018-08-03 03:33:26
回答 2查看 407关注 0票数 0

我正在尝试用Vanilla JS替换输入框。目前,我正在使用jquery这样做。

column.replaceWith("<select id='" + column[0].id + "' name='" + column[0].id + "' class='" + column[0].className + "'></select>");

我正在将我所有的代码重构为Vanilla JS,这是我最后需要做的事情。我已经完成了选择(‘document.createElement’);这就创建了<select></select>元素。然后我试着去做;

newEl.innerHTML += '<select id="selBidReceivedIsPM" name="selBidReceivedIsPM">'
                + '<option value="0">AM</option>'
                + '<option value="1">PM</option>';

,但这不会创建id或名称。在过去的3个小时里,我一直在搜索和尝试,需要一些帮助来弄清楚这一点。

html:

 <label for="columnA5"></label>
 <input
       type="number"
       id="columnA5"
       name="columnA5"
       class="columnA"
       step="any"
 >
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-03 03:47:55

类似这样的代码应该可以用来创建具有value和innerHTML选项的select。

var select = document.createElement('select');
select.id="selBidReceivedIsPM" 
select.name="selBidReceivedIsPM"
var val=2;
var time=["AM","PM"];
for (var i = 0; i<val; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = time[i];
    select.appendChild(opt);
}
console.log(select)

票数 1
EN

Stack Overflow用户

发布于 2018-08-03 03:58:54

我认为,如果DOM元素不是由javascript创建的,而是呈现出来的,你就不能“删除”它(在你的例子中是input type="number"...)。

您可以通过“隐藏”input来“替换”它,并将select元素放在“他”的位置上。

这里有个例子,试一下:

function replaceEle() {
  var txt=document.getElementById('columnA5');
  /*
   or You can use querySelectorAll :
   var txt=document.querySelectorAll('input[type="number"]');
   then You'll get all textboxes in page, and then You have to use for loop
  */
  var sel=document.createElement('select'); //create select element
  sel.id='selBidReceivedIsPM';
  sel.setAttribute('onchange','alert(this.value)'); 
  /*show selected value, or instead alert You can type some JS
    function, what gonna do when option is changed */
  var opt=document.createElement('option'); //create option element
  opt.value=0;opt.innerHTML='AM';
  sel.appendChild(opt); //add option element into select element
  opt=document.createElement('option');
  opt.value=1; opt.innerHTML='PM';
  sel.appendChild(opt);
  sel.selectedIndex=0; //set default selected value
  txt.style.display='none'; //hide input element
  txt.parentNode.insertBefore(sel, txt); //insert select element just before input, 
  
}
<input type="number" id="columnA5" value=""/><br>
<input type="button" value="Replace it" onclick="replaceEle();"/>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51660956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档