4

I made a way to add and remove fields using the input[type"number"]. I use jquery to do this but the way I did is not perfect. If there's a value in the field, the value will get erase if the number value is change because of using .remove(). Is there a better way to doing this?

<body>
    <input type="number" id="num" min="0" max="20" required/>
    <div class="dynamicInput"></div>
</body>

<script>
    $('#num').bind('keyup mouseup', function () {
        $('.dynamicInput .row').remove();
        $('.dynamicInput h4').remove();
        if ($(this).val() > 0) {
            $('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
            var num = $(this).val();
            for (var i = 0; i < num; i++) {
                $('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
            }
        }
    });
</script>

My Fiddle

4
  • 2
    Side note, as of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
    – j08691
    Commented Sep 3, 2015 at 16:16
  • So you want the data to be persist?
    – taesu
    Commented Sep 3, 2015 at 16:17
  • So if #num is 5, then 2, then 4 you'll lose the values that were in "3 & 4" since they're removed (and re-added)? Commented Sep 3, 2015 at 16:27
  • Instead of deleting it, why don't you just hide it?
    – Barmar
    Commented Sep 3, 2015 at 16:35

6 Answers 6

3

Try something like this. Instead of removing all of the inputs every time, this just removes the ones on the end, or adds more to the end.

The main difference between this one and yours is that I added var totNum = 0; to keep track of the current number of input there are. I then used that to determine how many to add/remove.

var totNum = 0;
$(document).on('keyup mouseup', '#num', function(){
  var num = $(this).val();
  if (num != "")
  {
    if (totNum == 0)
       $('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
    for (var i = num; i < totNum; i++)
    {
       $('.dynamicInput .row:last-child').remove();
    }
    for (var i = totNum; i < num; i++)
    {
       $('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
    }
    totNum = num;

    if (totNum == 0)
    {
       $('.dynamicInput h4').remove();
       $('.dynamicInput .row').remove();
    }
  }
});
input[type="number"] {
  width: 200px;
  height: 30px;
  font-family: Arial, sans-serif;
  font-size: 20px;
}
.row {
  display: block;
  margin-bottom: 15px;
}
body {
  width: 100%;
  padding: 40px;
}
input[type="text"] {
  width: 100%;
}
.col1,
.col2 {
  width: 45%;
  display: inline-block;
  margin-right: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<body>
  <input type="number" id="num" min="0" max="20" required/>
  <div class="dynamicInput"></div>
</body>

2
  • Could you add some explanation of what you changed?
    – Barmar
    Commented Sep 3, 2015 at 16:35
  • 1
    This is a great solution. Thanks!
    – OpuLance
    Commented Sep 3, 2015 at 18:07
2

It's easier and less likely to fail using a data structure as a skeleton upon which you can build the view. Note that this technique requires an extra computation in order to save user inputs, this is the reason why I've added the "change" event.

In the following code snippet, I've made two panels side by side. The left one is a list of inputs, very close to yours, easy to adapt to your needs, while the right one allows to see the evolution of the "data" array according to user actions.

Both panels rely on the "data" array, in other words, as soon as new items are added to or removed from "data", or a single item is updated, both panels are fully rebuilt. Note that the "change" event takes advantage of event delegation in order to deal with newly added inputs.

Finally, the "update" functions update the entire data source or a single item of the data source when the corresponding input changes, while the "render" functions draw on the data source to keep the panels in sync with the data. By the way, the right panel is rendered once at starting.

$(function () {

  var data = []; // data source
  var $num = $('#num'); // input for number of rows
  var $left = $('#left'); // left panel
  var $right = $('#right'); // right panel
  
  // render the right panel at starting

  renderRightPanel();

  // when the number of rows changes:
  //  - rebuild the left panel entirely
  //  - keep the data list up to date
  //  - print the array to the right panel

  $num.on('keyup mouseup', function () {
    renderLeftPanel($(this).val());
    updateList();
    renderRightPanel();
  });

  // when a value changes:
  //  - keep the data item up to date
  //  - print the array to the right panel

  $left.on('change', 'input', function () {
    var i = $left.find('input').index(this);
    updateItem(i, $(this).val());
    renderRightPanel();
  });

  // updates the data list

  function updateList () {
    data = $left.find('input').map(function () {
      return $(this).val();
    }).get();
  }

  // updates a single data item

  function updateItem (index, value) {
    data[index] = value;
  }

  // refreshes the DOM of the right panel

  function renderRightPanel () {
    $right.html('<pre>data = ' + (
      JSON.stringify(data, 0, 4)
    ) + '</pre>');
  }

  // refreshes the DOM of the left panel

  function renderLeftPanel (nLines) {
    var i;
    var html = '';
    if (nLines > 0) {
      html = '<h4>Heading</h4>';
      for (i = 0; i < nLines; i++) {
        html += '<div><input value="' + (data[i] || '') + '" /></div>';
      }
    }
    $left.html(html);
  }
});
body * {
  padding: 0;
  margin: 0;
}

h4, input {
  margin-bottom: .5em;
}

#panels {
  border: 1px solid black;
}

#panels > div {
  display: table-cell;
  padding: 1em;
}

#right {
  border-left: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panels">
  <div id="left"></div
  ><div id="right"></div>
</div>

3
  • Very nice, however your explanation needs some work. My answer relied upon the dom, yours generates the dom from the data. In keeping with the posters use of keyup, I'd modify your change listener also. Upvoted.
    – B2K
    Commented Sep 4, 2015 at 14:37
  • @B2K Don't blame me, but I'm not sure to understand your comment :-/ This solution is probably not the best option, mostly because the entire DOM is rebuilt I guess (think of React though), but nothing prevents us from changing this in favor to finer DOM manipulations. What matters here is that there is a data structure that is entirely free from rendering responsabilities, which makes things cleaner and easier to manage (in my opinion). Thanks for your vote though, it's still pleasant to see that some folks care about what you write :-)
    – user1636522
    Commented Sep 4, 2015 at 15:13
  • I had to run your snippet and think about it for a bit to understand what you were proposing.
    – B2K
    Commented Sep 4, 2015 at 15:23
1

Disable and hide extra elements instead of removing them. That will prevent them from getting posted, and also retain the previous value of all values that have been entered. See fiddle

One last point, if you don't want to retain values of hidden elements, change .hide() to .hide().val("")

<body>
    <input type="number" id="num" min="0" max="20" required/>
    <div class="dynamicInput">
        <h4>Please fill in the name and email of each extra attendees</h4>
    </div>
</body>

<style>
    .col1, .col2 { display: inline; width: 48%; margin-right: 2%; }
    .row { padding: 5px; }
</style>

<script>
    for (var i = 0; i < 20; i++) {
        $('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
    }
    $('#num').bind('keyup mouseup', function () {
        var num = parseInt($(this).val());
        $('.dynamicInput .row')
            .slice(num)
            .hide()
            .attr('disabled','disabled');
        if ( num > 0) {
            $('.dynamicInput .row')
                 .slice(0,num).show()
                 .removeAttr('disabled');
            $('.dynamicInput h4').show();
        } else {
            $('.dynamicInput h4').hide();
        }
    }).trigger('keyup');
</script>
0

Off-hand, you could cache the values within javascript to resist losing them between #num changes. e.g.

(function($){
  var $num = $('#num'),
      $dynamic = $('.dynamicInput');
      cache = {};
  
  $dynamic.on('change', 'input', function(e){
    cache[$(this).prop('name')] = $(this).val();
  });
  
  $num.on('change keyup mouseup', function(e){
    $dynamic.empty();
    
    var val = parseInt($(this).val(), 10);
    if (!isNaN(val) && val > 0){
      $('<h4>')
        .text('Please fill in the name and email of each extra attendees')
        .appendTo($dynamic);
      for (var i = 0; i < val; i++){
        
        var nameName = 'attendeesName' + i,
            emailName = 'attendeesEmail' + i;
        
        var $row = $('<div>',{'class':'row'}),
            $col1 = $('<div>',{'class':'col1'}).appendTo($row),
            $col2 = $('<div>',{'class':'col2'}).appendTo($row);
        
        $('<input>',{
          'type': 'text',
          'name': nameName,
          'placeholder': 'Name',
          'required': 'true'
        }).val(cache[nameName] || '').appendTo($col1);
        $('<input>',{
          'type': 'email',
          'name': emailName,
          'placeholder': 'Email',
          'required': 'true'
        }).val(cache[emailName] || '').appendTo($col2);
        
        $row.appendTo($dynamic);
      }
    }
  });
  
})(jQuery);
input[type="number"] {
    width:200px;
    height:30px;
    font-family:Arial, sans-serif;
    font-size:20px;
}
.row {
    display:block;
    margin-bottom:15px;
}
body{
    width:100%;
    padding:40px;
}
input[type="text"]{
    width:100%;
}
.col1, .col2{
    width:45%;
    display:inline-block;
    margin-right:10px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>

0

Here is an attempt to improve the accepted answer:

$(function () {

  var $num = $('#num');
  var $panel = $('#panel');
  var h4 = '<h4>Heading</h4>';
  var row = '<div><input /></div>';

  $num.on('mouseup keyup', function () {
    var n, $inputs;
    var value = $(this).val();
    if (value <= 0) {
      $panel.empty();
    }
    else {
      $inputs = $panel.find('input');
      // get the number of inputs already added
      n = $inputs.size();
      // add your heading if there is no input
      if (n === 0) {
        $panel.append(h4);
      }
      // the user wants less inputs
      if (value < n) {
        $inputs.slice(value).remove();
      }
      // the user wants more inputs
      else if (value > n) {
        $panel.append( 
          // a little trick, see below
          new Array(value - n + 1).join(row)
        );
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panel"></div>

A word on the "array join trick":

var a = [1, 2, 3, 4];
console.log(a.join('+'));
// prints "1+2+3+4"

var b = new Array(4); // an array of 4 undefined items
console.log(b.join('+'));
// prints "+++"

var c = new Array(3);
console.log('<ul>' + c.join('<li>item</li>') + '</ul>');
// prints "<ul><li>item</li><li>item</li></ul>"
-2

This is what exactly you are looking for,

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
 $(document).ready(function(){
    $("#num").keyup(function(){
    $('.dynamicInput .row').remove();
    $('.dynamicInput h4').remove();
    if ($(this).val() > 0) {
        $('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
        var num = $(this).val();
        for (var i = 0; i < num; i++) {
            $('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
        }
    }
    });
});
</script>
</head>
<body>
    <input type="number" id="num" min="0" max="20" required/>
    <div class="dynamicInput"></div>
</body> 
</html>
1
  • Consider expanding your answer to explain to the asker why this achieves the desired result, possibly linking to documentation. As is, this is only marginally useful. Commented Sep 3, 2015 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.