动态添加通过json创建的选择项

时间:2015-04-09 10:42:03

标签: javascript jquery json

我必须使用json数组的选择值动态创建表行 行被添加到行但下一个下拉列表不能在以下代码中工作当我试图连接选择的id与该调用函数我得到错误。我附加了jsfiddle的链接我在我没有收到错误只有选择下拉列表点头添加额外的字段here。如何解决错误与链接相同的效果。

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>
<body>

<h4> Honours Selection</h4>  
<table class="tg" style="undefined;table-layout: fixed; width: 657px"  id="customFields" >
<colgroup>
<col style="width: 222px">
<col style="width: 216px">
<col style="width: 219px">
<col style="width: 219px">
<col style="width: 219px">
<col style="width: 219px">
<col style="width: 219px">
<col style="width: 219px">
<col style="width: 219px">
<col style="width: 219px">
</colgroup>
  <tr>
    <th class="tg-hgcj" rowspan="2"><br>Honours</th>
    <th class="tg-hgcj" colspan="4">General</th>
    <th class="tg-hgcj" colspan="2">Bank Transaction Details</th>
    <th class="tg-hgcj"rowspan="2" >Add More</th>
  </tr>
  <tr>
    <td class="tg-093g">Sub1</td>
    <td class="tg-093g">Sub2</td>
    <td class="tg-093g">Sub3</td>
    <td class="tg-093g">Sub4</td>
    <td class="tg-093g">Bank Transaction id</td>
    <td class="tg-093g">Bank Transaction date</td>
  </tr>
  <tr>
    <td class="tg-30rh"><select name ="hons[]" id="select1"onchange="">
    <option value="Hindi">Hindi</option>
    <option value="Bengali">Bengali</option>
    <option value="English">English</option>
</select>

<select id="ddl2" name="session[]">
</select>
</td>
<td class="tg-30rh"> <select name="sub1[]"id="select2">
              </select>
</td>
<td class="tg-30rh"><select name="sub2[]"id="select3">
</select></td>
<td class="tg-30rh"><select name="sub3[]"id="select4">
</select></td>
<td class="tg-30rh"><select name="sub4[]"id="select5">
</select></td>
    <td class ="tg-30rh"><input type="text" name="tran_id[]"></td>
    <td class ="tg-30rh"><input type="text" name="tran_date[]"></td>
    <td><a href="javascript:void(0);" class="addCF">Add</a></td>
  </tr>
</table>

</body>
</html>
<script>

    $(document).ready(function(){var x=2;
    $(".addCF").click(function(){
        $("#customFields").append('<tr>\
    <td class="tg-30rh"><select name ="hons[]" id='+'select1'+x+' onchange="updateSelect(this.id);">\
    <option value="Hindi">Hindi</option>\
    <option value="Bengali">Bengali</option>\
    <option value="English">English</option>\
</select>\
<select id="ddl2" name="session[]">\
</select>\
</td>\
<td class="tg-30rh"> <select name="sub1[]" id='+'select2'+x+'>\
              </select>\
</td>\
<td class="tg-30rh"><select name="sub2[]" id='+'select3'+x+'>\
</select></td>\
<td class="tg-30rh"><select name="sub3[]" id='+'select4'+x+'>\
</select></td>\
<td class="tg-30rh"><select name="sub4[]" id='+'select4'+x+'>\
</select></td>\
    <td class ="tg-30rh"><input type="text" name="tran_id[]"></td>\
    <td class ="tg-30rh"><input type="text" name="tran_date[]"></td>\
    <td><a href="javascript:void(0);" class="remCF">Remove</a></td>\
  </tr>');x++;
    });
    $("#customFields").on('click','.remCF',function(){
        $(this).parent().parent().remove();
    });
});

var jsonObj = {"Hindi":[["History","Sociology","Economics"],"Philosophy","Political Science","English"],"Bengali":[["History","Sociology"],"Sanskrit","Philosophy","Political Science"],"English":[["History","Sociology","Economics"],"Philosophy","Political Science",["Bengali","Hindi"]],"History ":["Philosophy"," Political Science",["Bengali"," Hindi"]," English"],"Political Science":[[" History "," Sociology"," Economics"],"Philosophy",["Bengali "," Hindi"],"English"],"Philosophy":[[" History"," Sociology"]," Sanskrit","Political Science",["Bengali","Hindi"]]}

function updateSelect(id) {
    //alert("#"+id+"1");
    var getOpts = function(raw){
        var values = raw;
        if (!(raw instanceof Array)){
            values = [raw, ""];
        }
        var result = [];
        values.forEach(function(obj){
            result.push(new Option(obj, obj));
        });
        return result;
    };


    var newKey = $("#"+id+"1").val();
    var mappings = [{"#"+id+"2":0},{"#"+id+"3":1},{"#"+id+"4":2},{"#"+id+"5":3}];//getting error in this line SyntaxError: missing : after property id var mappings = [{"#"+id+"2":0},{"#"+id+"3":1}, {"#"+id+"4":2},//{"#"+id+"5":3} ]; near +

    var selected = jsonObj[newKey];

    mappings.forEach(function(mapping){
        var selector = Object.keys(mapping)[0];
        var index = mapping[selector];
        $(selector).empty();
        var opts = getOpts(selected[index]);
        $(selector).append(opts);
    });

}

$(document).ready(function() { 
    $("#select1").change(updateSelect);
    updateSelect(); // For initial page load.
});
</script>

2 个答案:

答案 0 :(得分:1)

那是因为你有拼写错误,请格式化你的代码,然后决定是否需要提问。

var mappings = [{"#"+id+"2":0},{"#"+id+"3":1},{"#"+id+"4":2},{"#"+id+5":3}];//getting error in this line 

格式化代码

var mappings = [
    {"#"+id+"2":0},
    {"#"+id+"3":1},
    {"#"+id+"4":2},
    {"#"+id+5":3}   // <- Do you see the error now?
];

固定

var mappings = [
    {"#"+id+"2":0},
    {"#"+id+"3":1},
    {"#"+id+"4":2},
    {"#"+id+"5":3}   // <- Fixed, you need to add the opening quote before the '5'.
];

我分叉你的JSFiddle并稍微清理一下:jsfiddle.net/b55bykec

更新

您需要构建映射,因为您无法生成与对象定义内联的动态键:

var mappings = [2, 3, 4, 5].reduce(function(map, val, index) {
    var key = '#' + id + val;
    map[key] = index;
    return map;
}, {});

var selected = jsonObj[newKey];

$.each(mappings, function (selector, index) {
    $(selector).empty().append(getOpts(selected[index]));
});

需要更改一些更改才能使代码正常工作。下面的所有以下更改都是为了使底部的工作示例工作。

  • 我将所有内联样式移动到样式表。您拥有许多相同的价值观,因此整合可以帮助您在未来更好地管理。
  • 我将customFields更改为custom-fields。 CSS类名和ID不应该是camelcase。单词通常用连字符分隔。这可能听起来很迂腐,但它可以帮助您将它们与JavaScript变量混淆。
  • 我将x移到全局范围内。 x是一个静态值,每次添加新行时都应自动增加。
  • 你有两个&#34; select4&#34; ID添加到每个动态行。我将第二个更改为&#34; select5&#34;。
  • 您生成的ID不够独特,我添加了一个破折号来分隔col-row。

    '<select name ="hons[]" id="' + 'select1-' + x + '">'
    
  • 为了让所有新的选择框都能监听更改事件,您需要将监听器添加到父容器并监听子容器的更改。

    $('#custom-fields').on('change', 'select[id^="select1-"]', updateSelect);
    

工作示例

&#13;
&#13;
var x = 1;

$(document).ready(function() {
  $(".addCF").click(function() {
    $("#custom-fields").append([
      '<tr>',
      '<td class="tg-30rh">',
      '<select name ="hons[]" id="' + 'select1-' + x + '">',
      '<option value="Hindi">Hindi</option>',
      '<option value="Bengali">Bengali</option>',
      '<option value="English">English</option>',
      '</select> ',
      '<select id="ddl2" name="session[]"></select>',
      '</td>',
      '<td class="tg-30rh">',
      '<select name="sub1[]" id="select2-' + x + '"></select>',
      '</td>',
      '<td class="tg-30rh">',
      '<select name="sub2[]" id="select3-' + x + '"></select>',
      '</td>',
      '<td class="tg-30rh">',
      '<select name="sub3[]" id="select4-' + x + '"></select>',
      '</td>',
      '<td class="tg-30rh">',
      '<select name="sub4[]" id="select5-' + x + '"></select>',
      '</td>',
      '<td class="tg-30rh">',
      '<input type="text" name="tran_id[]" />',
      '</td>',
      '<td class ="tg-30rh">',
      '<input type="text" name="tran_date[]" />',
      '</td>',
      '<td>',
      '<a href="javascript:void(0);" class="remCF">Remove</a>',
      '</td>',
      '</tr>'
    ].join(''));

    $('#select1-' + x).trigger('change');

    x++;
  });
  $("#custom-fields").on('click', '.remCF', function() {
    $(this).parent().parent().remove();
  });
});

var jsonObj = {
  "Hindi": [
    ["History", "Sociology", "Economics"], "Philosophy", "Political Science", "English"
  ],
  "Bengali": [
    ["History", "Sociology"], "Sanskrit", "Philosophy", "Political Science"
  ],
  "English": [
    ["History", "Sociology", "Economics"], "Philosophy", "Political Science", ["Bengali", "Hindi"]
  ],
  "History ": ["Philosophy", " Political Science", ["Bengali", " Hindi"], " English"],
  "Political Science": [
    [" History ", " Sociology", " Economics"], "Philosophy", ["Bengali ", " Hindi"], "English"
  ],
  "Philosophy": [
    [" History", " Sociology"], " Sanskrit", "Political Science", ["Bengali", "Hindi"]
  ]
};

function updateSelect(e) {
  var targetId = e.target.id;
  var id = parseInt(targetId.match(/[\w\d]+\-(\d+)$/)[1], 10);

  var getOpts = function(raw) {
    raw = Array.isArray(raw) ? raw : [raw, ''];

    return raw.map(function(obj) {
      return new Option(obj, obj);
    });
  };

  var newKey = $('#select1-' + id).val();

  var mappings = [2, 3, 4, 5].reduce(function(map, val, index) {
    var key = '#select' + val + '-' + id;
    map[key] = index;
    return map;
  }, {});

  var selected = jsonObj[newKey];

  $.each(mappings, function (selector, index) {
    $(selector).empty().append(getOpts(selected[index]));
  });
}

$(document).ready(function() {
  $('#custom-fields').on('change', 'select[id^="select1-"]', updateSelect);     
  $('#select1-0').trigger('change'); // For initial page load.
});
&#13;
.col-wide {
  width: 222px;
}

.col-narrow {
  width: 216px;
}

.col-normal {
  width: 219px;
}

#custom-fields {
  table-layout: fixed;
  width: 657px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<h4> Honours Selection</h4> 
<table class="tg" id="custom-fields">
  <colgroup>
    <col class="col-wide" />
    <col class="col-narrow" />
    <col class="col-normal" />
    <col class="col-normal" />
    <col class="col-normal" />
    <col class="col-normal" />
    <col class="col-normal" />
    <col class="col-normal" />
    <col class="col-normal" />
    <col class="col-normal" />
  </colgroup>
  <tr>
    <th class="tg-hgcj" rowspan="2">
      <br />Honours
    </th>
    <th class="tg-hgcj" colspan="4">General</th>
    <th class="tg-hgcj" colspan="2">Bank Transaction Details</th>
    <th class="tg-hgcj" rowspan="2">Add More</th>
  </tr>
  <tr>
    <td class="tg-093g">Sub1</td>
    <td class="tg-093g">Sub2</td>
    <td class="tg-093g">Sub3</td>
    <td class="tg-093g">Sub4</td>
    <td class="tg-093g">Bank Transaction id</td>
    <td class="tg-093g">Bank Transaction date</td>
  </tr>
  <tr>
    <td class="tg-30rh">
      <select name="hons[]" id="select1-0" onchange="">
        <option value="Hindi">Hindi</option>
        <option value="Bengali">Bengali</option>
        <option value="English">English</option>
      </select>
      <select id="ddl2" name="session[]">
      </select>
    </td>
    <td class="tg-30rh">
      <select name="sub1[]" id="select2-0">
      </select>
    </td>
    <td class="tg-30rh">
      <select name="sub2[]" id="select3-0">
      </select>
    </td>
    <td class="tg-30rh">
      <select name="sub3[]" id="select4-0">
      </select>
    </td>
    <td class="tg-30rh">
      <select name="sub4[]" id="select5-0">
      </select>
    </td>
    <td class="tg-30rh">
      <input type="text" name="tran_id[]" />
    </td>
    <td class="tg-30rh">
      <input type="text" name="tran_date[]" />
    </td>
    <td><a href="javascript:void(0);" class="addCF">Add</a>
    </td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您不能将表达式作为属性名称。

更新:

尝试这样的事情:

var mappings = [];
["#"+id+"2","#"+id+"3","#"+id+"4","#"+id+"5"].forEach(function(e,i) {
    var o = {};
    o[e] = i;
    mappings.push(o);
});