【问题标题】:how to save value dynamically receiving from html form and send to server如何从html表单动态接收值并发送到服务器
【发布时间】:2017-12-16 13:53:58
【问题描述】:

我正在尝试创建将数据发送到 servlet 的表单。 在这里,我在单击按钮时动态添加了一些输入框。但是每当我输入数据并单击新的“添加数据”时,以前的数据都会丢失,并且不会出现在输入框中。 点击添加数据后的表单截图

我必须动态创建它。 但是,当我单击添加内容的添加数据时,我已经填充的数据字段值会消失,如屏幕截图所示。如何在那里保存数据? 然后如何在点击提交按钮时将整个表单数据发送到 servlet? 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>

【问题讨论】:

  • 当您使用 += 追加到元素的 innerHTML 时,整个现有元素内容将替换为您分配的新 HTML - 因此您丢失用户已经输入的所有数据,因为您甚至将现有字段替换为 new 字段。您已经在使用 jQuery,所以不要再乱用 innerHTML,而是使用 jQuery 方法来添加新元素。
  • “然后如何在单击提交按钮时将整个表单数据发送到 servlet?” - 太宽泛了。去研究如何使用 jQuery序列化表单,以及如何发出 AJAX 请求以将数据发送到服务器。

标签: javascript jquery html servlets forms


【解决方案1】:

因为您是动态创建元素,所以您必须使用“委托”来访问这些元素。 Here is a fiddle 我创建了一段时间来演示委托。如果您无法从那里解决问题,请发表评论,我会帮助您解决问题。

    <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');
});

【讨论】:

  • 我不知道如何在我的代码中使用委托,这样之前的数据就不会被删除。你能帮我吗?
  • 您可以使用 AJAX。那里有大量的教程。在服务器端,您可以使用会话。但如果您不想刷新页面,请使用 AJAX。
【解决方案2】:

请看这里: assignment to innerHTML causes the destruction of all child elements

你应该使用 appendChild 而不是 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);
}

别忘了将Add Data 按钮的类型更改为:type='buttom'

【讨论】:

  • 当我点击添加数据时,当我将 add_fields() 函数更改为您的代码时,页面会重新加载。
  • &lt;button class="btn btn-success btn-block" type="submit" onClick="add_fields()"&gt; Add Data&lt;/button&gt; 中将type='submit' 更改为type='button'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 2016-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多