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

时间:2018-02-09 19:28:48

标签: javascript jquery json html5

我想通过单击动态生成的复选框来创建一个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数组最终应该如下:

[ { "Utterance": "Hello World", "BREAKFAST" : 0, "Parking" : 1 ...... }, { "Utterance": "John Doe", "BREAKFAST" : 1, "Parking" : 1 ...... } ..... ]

由于

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

您可以向新tr添加一个类,并找到这些元素以获取所需的数据。我:<tr class='utterances'>

重要此方法正在使用您当前的动态HTML

let array = []; // Array with each selected row.
$("#tblText tbody tr.utterances").each(function() {
  let row = {}; // data for a specific selected row.

  let utteranceLength = $(this).children('td:eq(0)').children(' input[name="record"]:checked').length;

  if (utteranceLength === 1) { //Checked row      
    var utterance = $(this).children('td:eq(1)').text();
    row['utterance'] = utterance;
    row['checks'] = [];

    $(this).children('td:gt(1)').each(function() {         
      let $input = $(this).children('input');
      row['checks'].push({[$input.attr('name')] : $input.is(':checked') ? 1 : 0});
    }); 

    array.push(row); 
  }
});

$(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 class='utterances'><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(e) {
    e.preventDefault();
    let array = []; // Array with each selected row.
    $("#tblText tbody tr.utterances").each(function() {
      let row = {}; // data for a specific selected row.
      
      let utteranceLength = $(this).children('td:eq(0)').children(' input[name="record"]:checked').length;
      
      if (utteranceLength === 1) { //Checked row      
        var utterance = $(this).children('td:eq(1)').text();
        row['utterance'] = utterance;
        row['checks'] = [];
        
        $(this).children('td:gt(1)').each(function() {         
          let $input = $(this).children('input');
          row['checks'].push({[$input.attr('name')] : $input.is(':checked') ? 1 : 0});
        });  
        
        array.push(row);
      }      
    });
    
    console.log(array);
  
//    var arr = $('input[name="breakfast"]').map(function() {
  //    return $(this).is(':checked') ? 1 : 0;
    //}).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>

答案 2 :(得分:0)

感谢 @Barmar @Ele 让我指出正确的方向。

我设法解决了我的问题。下面是代码,它为我修复了它。

$( function ()
    {

        var uttIdx = 0;

        $( '#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 class='utterances'><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 ( e )
        {
            let utteranceData = $( "#tblText tbody tr" ).map( function ()
            {
                let row = {};
                $( this ).find( "td" ).each( function ()
                {
                    var checkbox = $( this ).find( ":checkbox" );
                    if ( checkbox.length )
                    {
                        if ( checkbox.attr( 'name' ) != 'record' )
                        {
                            row[checkbox.attr( 'name' )] = checkbox.is( ':checked' ) ? 1 : 0;
                        }
                    }
                    else
                        row.utterance = $( this ).text();
                });
                return row;
            }).get();

            console.log(JSON.stringify(utteranceData));
            
            /* AJAX call to send JSON to C# Web API to save into a JSON File */

            $.ajax({
                url: "http://localhost:1070/api/GenerateAnnotatedJSON",
                data: JSON.stringify( utteranceData ),
                method: "POST",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (data)
                {
                    console.log( data["message"] );
                    alert( data["message"]);
                },
                error: function ( jqXHR, errorThrown, statusText )
                {
                    console.log( data["errorThrown"] );
                }
            });
            
        });

        // 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>

最后,C#服务器端代码:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Net.Http.Formatting;

namespace AnnotatingTool.Controllers
{
    public class ValuesController : ApiController
    {
        [HttpPost]
        [Route("api/GenerateAnnotatedJSON")]
        public async Task<HttpResponseMessage> GenerateAnnotatedJSON([FromBody] List<JObject> UtteranceAnnotatedData)
        {
            try
            {
                string path = Path.Combine("D:", "Data", "data.json");
                string jsonContents = JsonConvert.SerializeObject(UtteranceAnnotatedData, new JsonSerializerSettings()
                {
                    Formatting = Formatting.Indented,
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

                File.WriteAllText(path, jsonContents);
                return new HttpResponseMessage()
                {
                    Content = new ObjectContent<JObject>(new JObject { new JProperty("message", "File successfully created") }, new JsonMediaTypeFormatter()),
                    StatusCode = HttpStatusCode.OK
                };
            }
            catch(Exception ex)
            {
                throw;
            }
        }
    }
}