javascript - 从附加的 HTML 元素更新 HTML 属性

标签 javascript jquery

用户正在添加新的搜索字段(输入字段+选择元素)。当用户从选择元素中选择时,我尝试更新输入元素中的“名称”值。不幸的是,以下代码会导致 console.log 行出现以下错误

TypeError:null 不是对象(评估“document.getElementById(selectID).options”)

这是代码:

function updateName2(index){

  var selectID = "SEL"+index;
  var inputID = "AS"+index;

  var e = document.getElementById(selectID);
  var valueSelect = e.options[e.selectedIndex].text;

  console.log(valueSelect); //error here

  document.getElementById(inputID).name = valueSelect;
};

var index = 2;

// ADD NEW SEARCH FIELD
$("#addNewSearchField").click(function() {
$("#Form").append(

  "<input id='AS"+index+"' type='text' name='' value=''>"+
  "<select id='SEL"+index+"' onChange='updateName2(index)'>"+
      "<?php
      foreach ($fields as $key => $value) {
        if($key=="select"){
          echo "<option selected value='".$key."'>".$value."</option>";
        }else{
          echo "<option value='".$key."'>".$value."</option>";}
        };
      ?>"
   +"</select><br>"
);
index += 1;
})

最佳答案

创建选择 block 时

"<select id='SEL"+index+"' onChange='updateName2(index)'>"+

您在其 id 中使用 index 变量,但在 onChange 的函数中您只需使用 index作为字符串,它不能正确引用变量。这意味着您正在运行 document.getElementById("SEL"+ undefined),它返回 null(因为这样的元素不存在)。

试试这个:

"<select id='SEL"+index+"' onChange='updateName2(" + index + ")'>"+

关于javascript - 从附加的 HTML 元素更新 HTML 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48214933/

相关文章:

javascript - 使用jquery从php文件到php文件的php变量

javascript - 如何使用 "controller as"语法从基本 Controller 继承?

jquery - 如何使用 jQuery 将文本转换为电子邮件链接

javascript - JQuery 函数作为单行工作,但当我将其分解时却不行

javascript - 以编程方式打开 Bootstrap Alert

javascript - 如何将类添加到 TinyMCE 表编辑器的下拉菜单中

javascript - OO JavaScript。属性(property)问题

javascript - 检查输入是否为空 JQuery

javascript - jQuery 不适用于 getJSON

jquery - 将 div 从屏幕外水平滑动到中心?