Svj
Svj

Reputation: 491

Bootstrap modal data refresh

I am trying to pass data from bootstrap modal to the ul element. It lets me to add multiple li elements but it is always the first li element and doesnt change. Please help.

<ul id="myList">
</ul>

<button type="button" id="btnLaunch" class="btn btn-primary">Add Item</button>
<div class="modal fade" id="myModal">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>
              </button>
              <h4 class="modal-title">Modal title</h4>
            </div>
            <div class="modal-body">
              <p>Enter text:</p>
              <input type="text" id="txtInput">
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" id="btnSave" class="btn btn-primary">Save changes</button>
            </div>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>
      <!-- /.modal -->
<script>
$(function() {
  $('#btnLaunch').click(function() {
    $('#myModal').modal('show');
  });

  $('#btnSave').click(function() {

    var value = $('input').val();
     $("#myList").append('<li><input type="checkbox" id="'+ value +'" name="'+ value +'" value="'+ value +'" checked>'+ value +'</li>');

        $('#myModal').modal('hide');


  });
});
</script>

Upvotes: 0

Views: 2030

Answers (1)

Muhammad Farhan Abrar
Muhammad Farhan Abrar

Reputation: 48

Use this:

 $('#txtInput').val();

instead of

 $('input').val();

You are using just input selector on every iteration which is too generic. You can use the Id selector from Jquery to grab the input element and get the new value out of it. Here is a working example.

 <script>
  $(function() {

   $('#btnLaunch').click(function() {
      $('#myModal').modal('show');
   });

   $('#btnSave').click(function() {

   var value = $('#txtInput').val();
   $("#myList").append('<li><input type="checkbox" id="'+ value +'" 
   name="'+ value +'" value="'+ value +'" checked>'+ value +'</li>');

   $('#txtInput').val('');

   $('#myModal').modal('hide');
  });
 });
 </script>

Upvotes: 1

Related Questions