繁体   English   中英

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

[英]Selecting multiple check-boxes for dynamically created elements

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

在此处输入图片说明

如果未选中此复选框,那么我想在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> 


这是工作的小提琴


更新:

JSON数组最终应该像:

[ { "Utterance": "Hello World", "BREAKFAST" : 0, "Parking" : 1 ...... }, { "Utterance": "John Doe", "BREAKFAST" : 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();

您可以将类添加到新的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> 

感谢@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;
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM