从附加的HTML元素更新HTML属性 [英] Update HTML attribute from appended HTML element

查看:93
本文介绍了从附加的HTML元素更新HTML属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

User is adding a new search field (input field + select element). When user selects from select element I am trying to update the "name" value from the input element. Unfortunately the following code results in the following error at the console.log line

TypeError: null is not an object (evaluating '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;
})

推荐答案

创建选择块时

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

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

You use the index variable in its id, but in the function in onChange you just use index as a string, which doesn't refer to the variable correctly. This means that you're running document.getElementById("SEL" + undefined), which returns null (as such an element does not exist).

尝试以下方法:

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

这篇关于从附加的HTML元素更新HTML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆