0

I'm trying to create form that send data to servlet. Here im adding some input box dynamically on Click of button. But whenever i enter data and click new "add data" , previous data get lost and it does not appear in input box. Screen shot of form after clicking Add Dataenter image description here

screen shot before clicking "Add data"

I'll have to create it dynamically. But when I click on add data of add content the data fields values the i have already filled diappears as shown in the screenshot. How to save the data there? And then how to send the whole form data to the servlet on click of submit button? code of html

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
function add_fields() {
console.log(document.getElementById('wrapper').innerHTML);
    document.getElementById('wrapper').innerHTML += "<br /><span>Step Number: <input name='step' type='number'style='width:75px;'value='' /></span>  <span> Add Content: <input type='button' onClick='addContent()' value='Add Content' /></span>";
console.log(document.getElementById('wrapper').innerHTML);
}
function addContent(){
console.log(document.getElementById('wrapper').innerHTML);
document.getElementById('wrapper').innerHTML +="<br /><span><input name='contentimage' type='text' placeholder='enter image url' /></span><span><input name='contentmessage' type='text' placeholder='enter message' /></span><span><input name='alert' type='text' placeholder='enter alert' /></span>";
console.log(document.getElementById('wrapper').innerHTML);
}
</script>
  <style>
  .modal-header, h4, .close {
      background-color: #5cb85c;
      color:white !important;
      text-align: center;
      font-size: 30px;
  }
  .modal-footer {
      background-color: #f9f9f9;
  }
  </style>
</head>
<body>

<div class="container">
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-default btn-lg" id="myBtn">Share Solutions</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header" style="padding:35px 50px;">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4>Add Solutions</h4>
        </div>
        <div class="modal-body" style="padding:40px 50px;">
          <form role="form">
            <div class="form-group">
              <label for="cost">Cost</label>
              <input type="text" class="form-control" name="cost" id="cost" placeholder="Enter cost">
            </div>
            <div class="form-group">
              <label for="difficulty">Difficulty</label>
              <input type="text" class="form-control" name="difficulty" id="difficulty" placeholder="Enter Difficulty">
            </div>
            <div class="form-group">
              <label for="image">Image</label>
              <input type="text" class="form-control" name="image" id="image" placeholder="Enter Image Url">
            </div>
             <div class="form-group">
              <label for="message">Message</label>
              <input type="text" class="form-control" name="message" id="message" placeholder="Enter Message">
            </div>
            <div class="form-group">
              <label for="title">Title</label>
              <input type="text" class="form-control" name="title" id="title" placeholder="Enter Title">
            </div>
            <div class="form-group">
              <label for="description">Description</label>
              <input type="text" class="form-control" name="description" id="description" placeholder="Enter Description">
            </div>
          <div class="form-group" id="wrapper">
              <label for="description">Data</label> <button  class="btn btn-success btn-block" type="submit" onClick="add_fields()"> Add Data</button>
          </div>
          <div>

          </div>                                                   
              <button type="submit" class="btn btn-success btn-block">Submit</button>
          </form>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal" onClick="window.location.reload()"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
        </div>
      </div>

    </div>
  </div> 
</div>

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myModal").modal();
    });
});
</script>

</body>
</html>
Joshi Yogesh
  • 142
  • 1
  • 12
  • When you _append_ to an element’s innerHTML using +=, the _whole_ existing element content gets replace with the new HTML you assign - and therefor you loose all data the user has already entered, because you are replacing even the existing fields with _new_ ones. You are using jQuery already, so stop messing around with innerHTML, and use the jQuery methods for appending new elements. – CBroe Jul 12 '17 at 08:48
  • _“And then how to send the whole form data to the servlet on click of submit button?”_ – way too broad. Go research how to _serialize_ a form using jQuery, and how to make an AJAX request to send the data to the server. – CBroe Jul 12 '17 at 08:48

2 Answers2

0

Because you're creating elements dynamically, you'll have to use "delegation" to access those elements. Here is a fiddle I created awhile back that demonstrates delegation. If you can't solve your problem from there, leave a comment and I'll help you through it.

    <p>This is to demonstrate how to use delegation to make dynamically created buttons (or any dynamically created element) respond to an event handler.</p>
<p>Note that in order to do this, there must be some element that loads with the DOM so that the listener can find the child element inside of it.</p>
<p>In this case, we're using the div with the id of "inside_div" as our pre-loaded element and then adding the button dynamically to that div when button 1 is clicked.</p>
<div id='test_div'>
    <button id='button1' value='button1'>Button 1</button>
    <div id='inside_div'></div>
</div>

    $('#button1').click(function () {    
    var btn_txt = "<br><button id='button2'>Button 2</button>";
    $('#inside_div').append(btn_txt);

});

//Note that a standard event listener will not work on Button 2 because
//it was created dynamically and so the event listener cannot find it.
//$('#button2').click(function(){
//  alert('button2 event');
//});


//Delegated event listener
//Note that we're referencing the element that loaded with the DOM ('#inside_div')
//Also note that insted of using a click event, we use .on() and then specificy 'click' inside of it.
//Because #inside_div already exists, we can then locate the 
//dynamically created child element inside of it.
$('#inside_div').on('click', '#button2', function () {    
    var i = 3;
    while (i <= 5) {
        var btn_txt = "<br><br><button class='test_class' id='button" + i + "' >Button " + i + "</button>";
        $('#inside_div').append(btn_txt);
        i++;
    }
});

//This is to demonstrate a listener that works on multiple elements with the same class.
$('#inside_div').on('click', '.test_class', function () {
    alert('Class Alert');
});
Difster
  • 3,264
  • 2
  • 22
  • 32
  • I don't know how to use delegation in my code so that the previous data won't get erased. Can you help me ? – Joshi Yogesh Jul 12 '17 at 09:40
  • You can use AJAX. There are tons of tutorials out there for that. On the server side you can use sessions. But use AJAX if you don't want your page to refresh. – Difster Jul 12 '17 at 09:59
0

See here: assignment to innerHTML causes the destruction of all child elements.

You should use appendChild instead innerHTML:

function add_fields() {
    var newElement = document.createElement('span'),
        newBr = document.createElement('br');
    newElement.innerHTML = "Step Number: <input name='step' type='number'style='width:75px;'value='' /></span>  <span> Add Content: <input type='button' onClick='addContent()' value='Add Content' />";

    document.getElementById("wrapper").appendChild(newBr);
    document.getElementById("wrapper").appendChild(newElement);
}

And don't forget change the Add Data button's type to: type='buttom'.

azlar
  • 460
  • 1
  • 5
  • 12