3

I am trying to get the value from an input into a cell of a table and I do not know why the val(); is not working(not getting the value). I have checked everywhere, here, here and here but with little success. I belive my code is correct. Am I missing something about the rendering or my code is wrong? All help will be apreciated.

thank you in advance

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); 
    var add_button      = $(".add_studies_button"); 
 var studies         = $("#studies").val();
 
    
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ 
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; 
            $(wrapper).append('<tr>' +
        '<td>' + studies + '</td>' +
        '<td>Que tal</td>' +
        '<td>Pitt</td>' +
        '<td>35</td>' +
        '<td>New York</td>' +
        '<td><a class="remove_field">Remove</a></td>' +
  '</tr>'); 
        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent().parent().remove(); x--;
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 

<div class="form-horizontal pull-right col-xs-6">
 
  <div class="form-group">
            <label class="col-lg-3 control-label">Studies:</label>
            <div class="col-lg-8">
              <input class="form-control" maxlength="100" type="text" id="studies" required="required"  placeholder="Studies">
            </div>
        </div>
          
  <div class="form-group">
            <label class="col-md-3 control-label"></label>
            <div class="col-md-8">
               <button class="btn btn-primary pull-right add_studies_button" style="margin-top:7px;">Add</button>
      
              <span></span>
     
     
            
            </div>
          </div>
  
  
   <div class="table-responsive col-xs-6">          
  <table class="table">
    <thead>
      <tr>
        <th>#</th>
        <th>Studies</th>
        <th>School</th>
        <th>From</th>
        <th>To</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody class="input_fields_wrap">
 
 
    
 
 
      
    </tbody>
  </table>
  </div>
Community
  • 1
  • 1
lostintheriver
  • 197
  • 1
  • 1
  • 12

1 Answers1

1

Try adding the statement:

var studies = $("#studies").val();

inside the click listener:

$(add_button).click(function(e) { 

This is so that it gets the value of the #studies input box at the time of click. The variable studies in your code is set at the beginning and never updated (it does not automatically update to the value of #studies).

See a working example here.

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94