简体   繁体   中英

How to capture the data from this dynamic form

I am using this bootsnipp for BootStrap.JS to create dynamic fields.

How can I capture the data from these dynamic fields as key value pairs?

And what if I have 2 sections on the same page that require these set of dynamic fields?

Any sample snippet would be helpful.

You need to find the selected li and get the text of it. I recommend adding value for every li but it is up to you afterall.I added id for your ul and checked it's action. The id i chose was "tryME" Anyway here is code you need:

$('#tryMe a').on('click', function(e) {
  e.preventDefault();

  // This removes the class on selected li's
  $("#tryMe li").removeClass("select");

  // adds 'select' class to the parent li of the clicked element
  // 'this' here refers to the clicked a element
  $(this).closest('li').addClass('select');

  // sets the input field's value to the data value of the clicked a element
  $('#tryMe').val($(this).text());
  console.log( $('#tryMe').val());
});

here is your snip updated on bootply: http://www.bootply.com/e3qqmab4SQ

I noticed one fatal flaw about this snippet is that there's no way to differentiate multiple instances of a field. If you enter 2 phone numbers, which one is which? I guess the data could be sorted out server side, but I'm just front end and no very little about the magical realm of the back end.

I added a button #data , a hidden input .cache , and a function collectData(ele) . The HTML and jQuery are annotated with the details on function and purpose of each important component.

 //
/* collectData Function~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~/ 
This function given a group of elements (in classic selector format) will assign each 
element the values of the closest fields as a unique name and the user entered value 
(if any.)
Use the console to see it gather data.
*/
        var collectData = function(ele) {
            var $tgt = $(ele);
            $tgt.each(function(index) {
// $tgt == $(this)
                var $fieldNames = $(this).next('.input-group-select-val').val();
                var $fieldValues=$(this).closest('.form-group').find('.form-control').val();

// Including index to each $fieldName in order to make each key/value pair unique.

                $(this).attr('name', $fieldNames+index);
                console.log('name: '+$(this).attr('name'));
                $(this).val($fieldValues);
                console.log('value: '+$(this).val());
              });
        }

DEMO: http://bootsnipp.com/user/snippets/xaAXG

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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