javascript - 为动态创建的元素选择多个复选框

标签 javascript jquery json html

我想通过单击动态生成的复选框来创建一个包含 0 和 1 值的 JSON 数组。

enter image description here

如果未选中该复选框,那么我想在 JSON 数组中存储 0,否则如果选中该复选框,我想存储 1。

更新: 当我在文本框中添加话语时,我还希望在单击提交按钮时将其值与 0 和 1 一起推送到 JSON 数组。

点击提交按钮后,我想生成所选条目的完整 JSON 对象。

<小时/>

这是我的代码:

$(function() {

    var uttIdx = 0;
    var utteranceData = new Array();

    $( '#btnDeleteRow' ).hide();

    $('#btnAddUtterance').click( function (){
            populateUtterance();
    });

    $("#myInput").keyup(function(event){
        //If user presses enter, the code will save into the table
        if (event.keyCode === 13)
        {
            populateUtterance();
        }
    });

    function populateUtterance()
    {
      $( '#btnDeleteRow' ).show();

      let userUtterance = $( '#myInput' ).val();

      let markup = `<tr><td><input type='checkbox' name='record'></td><td>${userUtterance}</td><td><input type='checkbox' name='Breakfast'></td><td><input type='checkbox' name='Parking'></td><td><input type='checkbox' name='KingBed'></td><td><input type='checkbox' name='QueenBed'></td><td><input type='checkbox' name='TwinBed'></td><td><input type='checkbox' name='StandardRoomType'></td><td><input type='checkbox' name='GuestRoomType'></td><td><input type='checkbox' name='DeluxeRoomType'></td><td><input type='checkbox' name='Accessible'></td><td><input type='checkbox' name='Concierge'></td><td><input type='checkbox' name='LoungeAccess'></td><td><input type='checkbox' name='ExecutiveLevel'></td></tr>`;
    
      $( "#tblText tbody" ).append( markup );

      uttIdx += 1;
      $('#myInput').val('');
  }


    $( '#btnSubmit' ).click( function (){
        var arr = $( 'input[name="breakfast"]:checked' ).map( function ()
        {
            return 1;
        } ).get();
        //Some thing like this? for every checkbox.
        //I need the sentence text also here.
        //utteranceData.push( { utterance: "", Breakfast: 0, .... } );
    });

  // Find and remove selected table rows
  $(document).on('click', '#btnDeleteRow', function(e) {
    $("#tblText tbody").find('input[name="record"]').each(function() {
      if ($(this).is(":checked")) {
        $(this).parents("tr").remove();
        $('#testOutput').html('');
      }
    });
  });
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<h2>AnnotationView</h2>

<h2>Enter text to annotate</h2>

<input type="text" id="myInput" />
<button id="btnAddUtterance" class="btn btn-info">Add Utterance</button>

<table id="tblText" class="table table-hover">
    <thead>
        <tr>
            <th>Select</th>
            <th>Utterance</th>
            <th>Breakfast</th>
            <th>Parking</th>
            <th>King Bed</th>
            <th>Queen Bed</th>
            <th>Twin Bed</th>
            <th>Standard Room Type</th>
            <th>Guest Room Type</th>
            <th>Deluxe Room Type</th>
            <th>Accessible</th>
            <th>Concierge</th>
            <th>Lounge Access</th>
            <th>Executive Level</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

<button id='btnDeleteRow' class='btn btn-danger'>Delete Utterance</button>
<button id="btnSubmit" class="btn btn-info">Submit</button>

<小时/>

<强> Here's the working fiddle

<小时/>

更新:

JSON 数组最终应该是这样的:

[ { “话语”:“ Hello World ”, “早餐”:0, “ parking 位”:1 ...... }, { “话语”:“约翰·多伊”, “早餐”:1、 “ parking 位”:1 ...... } …… ]

谢谢

最佳答案

不要在选择器中使用 :checked 修饰符,因为它只会处理选中的框。您想要处理所有框,并根据是否选中来返回不同的值。

var arr = $("input[name=breakfast]").map(function() {
    return this.checked ? 1 : 0;
}).get();

要获取包含表中所有数据的对象,如下所示:

var arr = $("tblText tbody tr").map(function() {
    var row = {};
    $(this).find("td").each(function() {
        var checkbox = $(this).find(":checkbox");
        if (checkbox.length) {
            row[checkbox.attr('name')] = checkbox.val();
        } else {
            row.utterance = $(this).text();
        }
    });
    return row;
}).get();

关于javascript - 为动态创建的元素选择多个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48712835/

相关文章:

javascript - 以背景图像为中心的文本 [CSS]

jQuery 从每个循环中获取数据并存储在全局变量中

jquery - jqgrid 和 jqPivot : How to remove grouping when xDimension have multi value?

jQuery :first vs. .first()

javascript - 将 JS 对象从一个 HTML 页面发送到另一个

javascript - ReactJS 是否将对象文字解析为字符串?

javascript - 如何使用 ng-tags-input 添加标签数组?

javascript - scrollIntoView() 没有将节点滚动到树的顶部

javascript - 如何在javascript中迭代嵌套数组对象

json - Entity Framework : How to map a complex object to a single varchar column (i. e。以序列化形式保存)?