How to create fields dynamically when selecting a value in the checkbox?

3

In this script below it counts checkbox checked.

How can I make it count, also add new fields <input type="text"> according to the amount of checked tagged

For example: I marked 5 box, then show 5 fields

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><scripttype='text/javascript'>//<![CDATA[window.onload=function(){varcontador=function(){varn=$("input:enabled:checked" ).length;

        $("#checkcount").text( n + (n === 1 ? " é" : " são") + " selecionadoss" );
     };
     contador(); 
     $( "input[type=checkbox]" ).on( "click", contador );
   }//]]> 
</script>

<input type="checkbox" name="check1" checked disabled  value="1">
<input type="checkbox" name="check1" value="2">
<input type="checkbox" name="check1" value="3">
<input type="checkbox" name="check1" value="4">
<input type="checkbox" name="check1" value="5">    
<div id="checkcount"></div>
    
asked by anonymous 05.01.2016 / 01:41

1 answer

2

Well, this can be done in a few ways, it will depend on what exactly you want with these text boxes.

I wrote an example that takes into account the order of elements, ie if you have checked 5 checkboxes, have 5 text boxes, uncheck the last box, the last text box will disappear, uncheck the second, the second will disappear ... See if it suits you.

Javascript

var contador = function() {
var n = $("input:enabled:checked").length;
var unchecked = 0;
var cb = $(this).index();
$("input:enabled").each(function(i) {
    if ((i < cb) && !($(this).is(":checked"))) {
      ++unchecked;
    }
  })

  if($(this).is(":checked")){
    $('body').append('<input type="text" class="created">');
  }else{
    $('.created').eq($(this).index()-unchecked).remove();
  }

$("#checkcount").text(n + (n === 1 ? " é" : " são") + " selecionadoss");
};
contador();
$("input[type=checkbox]").on("click", contador);

% of the% dynamically created% gave input text for easier manipulation.

The class="created" variable will receive the number of checked unchecked checkboxes before it was clicked, this value will be subtracted as the unchecked of the checked checkbox, this will result in the position of the element that will be cleared by unchecking the checkbox. I know it's confusing, but it's easy to adapt.

For some reason the same code that was in JsFiddle and works perfectly, does not work here, so I just left JsFiddle.

Example - JSFiddle

Inputs created inside a specific div

To do this simply replace the

$('body').append(...

By

$('sua div').append(...

Using the selector of index or id or whichever you prefer. Here's an example in JsFiddle

JsFiddle

I hope you have helped ...

    
05.01.2016 / 03:16