简体   繁体   中英

Get the values of Dynamically created elements using Jquery

I am dynamically creating input elements using jquery, but when I try to access the dynamically created element values, I'm getting either empty or undefined or . I tried many ways to get the values, but It is failing.

Could someone help me getting this done.

Here is the code

 $(document).ready(function() { var count = 0; var jsondata = []; var selectedField; $('.add').click(function() { count = count + 1; jQuery('<div/>', { id: 'form-wrapper' + count, class: 'form-wrapper' + count, title: 'now this div has a title!' }).appendTo('.wrapper0'); $('.form-wrapper' + count).append("<label>FieldName</label> <input type='text' placeholder='label' id='label" + count + "'></input> <select class='select" + count + "'><option>Select</option><option value='textbox'>Textbox</option><option value='textarea'>TextArea</option><option value='checkbox'>Checkbox</option><option value='radio'>Radio</option><option value='date'>Date</option> </select><input type='text' id='commavalues" + count + "' disabled placeholder='Enter comma(,) seperated values'></input><input type='checkbox' id='required" + count + "'>Required</input><button class='delete'>Delete</button> <br><br>"); $('.delete').click(function(e) { ($(this).parent().remove()); }); $('.select' + count).change(function() { selectedField = $(this).children('option:selected').val(); if (selectedField == 'checkbox' || selectedField == 'radio') { $('#commavalues' + count).prop('disabled', false); flag = 1; } else { flag = 0; $('#commavalues' + count).prop('disabled', true); } }); item = {}; var label = $('#label' + count).val(); var required = $('#required' + count).is(":checked"); var label_type = selectedField; var options = $('#commavalues' + count).val(); console.log(label); console.log(required); console.log(label_type); console.log(options); item["label"] = label; item["label_type"] = label_type; item["options"] = options; item["required"] = required; jsondata.push(item); }); $('.save').click(function() { console.log(jsondata); }); }); 
 body { background-color: #ECEFF1; margin: 50px 0; padding: 0; text-align: center; } button { position: relative; margin-left: 0px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper0"> <div class="form-wrapper"> <label>FieldName</label> <input type="text" placeholder="label" class="label0"></input> <select class="select0"> <option>Select</option> <option value="textbox">Textbox</option> <option value="textarea">TextArea</option> <option value="checkbox">Checkbox</option> <option value="radio">Radio</option> <option value="date">Date</option> </select> <input type="text" class="commavalues0" disabled placeholder="Enter comma(,) seperated values"></input> <input type="checkbox" class="required0">Required</input> <br><br> </div> </div> <button class="add">Add</button> <button class="save">Save</button> 

I am trying to display in JSON format when I click save button, and If i click the delete button the data associated to that input fields are to be deleted also.

One problem is that all your closures are using the same count variable, which gets incremented each time another element is added. They need a local variable for each closures.

But it would better to get rid of that variable entirely. Just give them all the same class, and use event delegation to bind to dynamically added elements. See Event binding on dynamically created elements? for detailed explanations.

The other problem is that you're getting the values when you add the elements, not when the user clicks the Save button. When that happens you need to loop through all the elements.

 $(document).ready(function() { $('.add').click(function() { var form_wrapper = jQuery('<div/>', { class: 'form-wrapper', title: 'now this div has a title!', html: "<label>FieldName</label> <input type='text' placeholder='label' class='label'></input> <select class='select'><option>Select</option><option value='textbox'>Textbox</option><option value='textarea'>TextArea</option><option value='checkbox'>Checkbox</option><option value='radio'>Radio</option><option value='date'>Date</option> </select><input type='text' class='commavalues' disabled placeholder='Enter comma(,) seperated values'></input><input type='checkbox' class='required'>Required</input><button class='delete'>Delete</button> <br><br>" }).appendTo('.wrapper0'); }); $('.save').click(function() { var jsondata = $(".form-wrapper").map(function() { var label = $(this).find(".label").val(); var required = $(this).find(".required").is(":checked"); var label_type = $(this).find(".select").val(); var options = $(this).find(".commavalues").val(); return { label, required, label_type, options }; }).get(); console.log(jsondata); }); $(".wrapper0").on("click", ".delete", function(e) { ($(this).parent().remove()); }); $(".wrapper0").on("change", '.select', function() { var selectedField = $(this).val(); if (selectedField == 'checkbox' || selectedField == 'radio') { $(this).siblings('.commavalues').prop('disabled', false); } else { $(this).siblings('.commavalues').prop('disabled', true); } }); }); 
 body { background-color: #ECEFF1; margin: 50px 0; padding: 0; text-align: center; } button { position: relative; margin-left: 0px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper0"> <div class="form-wrapper"> <label>FieldName</label> <input type="text" placeholder="label" class="label"></input> <select class="select"> <option>Select</option> <option value="textbox">Textbox</option> <option value="textarea">TextArea</option> <option value="checkbox">Checkbox</option> <option value="radio">Radio</option> <option value="date">Date</option> </select> <input type="text" class="commavalues" disabled placeholder="Enter comma(,) seperated values"></input> <input type="checkbox" class="required">Required</input> <br><br> </div> </div> <button class="add">Add</button> <button class="save">Save</button> 

Hey i have fixed undefined error and seems working as expected. you can replace below code in script.

<script>
$(document).ready(function(){
   var count = 0;
   var jsondata=[];
   var selectedField;
   $('.add').click(function(){
      jQuery('<div/>', {
         id: 'form-wrapper'+count,
         class: 'form-wrapper'+count,
         title: 'now this div has a title!'
      }).appendTo('.wrapper0');
      $('.form-wrapper'+count).append("<label>FieldName</label> <input type='text' placeholder='label' class='label"+(count+1)+"'></input> <select class='select"+(count+1)+"'><option>Select</option><option value='textbox'>Textbox</option><option value='textarea'>TextArea</option><option value='checkbox'>Checkbox</option><option value='radio'>Radio</option><option value='date'>Date</option> </select><input type='text' class='commavalues"+(count+1)+"' disabled placeholder='Enter comma(,) seperated values'></input><input type='checkbox' class='required"+(count+1)+"'>Required</input><button class='delete'>Delete</button> <br><br>");

      $('.delete').click(function(e){
         ($(this).parent().remove());
      });
      item = {};

      var label = $('.label'+count).val();
      var required = $('.required'+count).prop("checked");
      var label_type = selectedField;
      var options = $('.commavalues'+count).val();

      console.log(label);
      console.log(required);
      console.log(label_type);
      console.log(options);

      item["label"] = label;
      item["label_type"] = label_type;
      item["options"] = options;
      item["required"] = required;
      jsondata.push(item);
      count++;
   });

   $('.save').click(function(){
      console.log(jsondata);
   });
   $('.select'+count).on('change', function(){
         selectedField = $(this).find('option:selected').text();
         if(selectedField == 'checkbox' || selectedField == 'radio'){
           $('#commavalues'+count).prop('disabled', false);
           flag = 1;
        }
       else{
            flag = 0;
            $('#commavalues'+count).prop('disabled', true);
       }
    });
});
</script>

dynamically or not elements in the DOM are the sames. JQuery is JavaScript and can't do something out of JavaScript. JavaScript is mainly about DOM and DOM is HTML about elements, attributes and properties of those. So there is not propertie .value for div, instead you've to use Javascript .innerHTML (or even outerHTML) who in JQuery can be accessed by .html() or .text() regarding you want to manipulate plain HTML(who're object in DOM) or text. The .value propertie is about inputs or such elements in a HTML form tag. Hoping that'll help you.

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