jquery add/remove before/after

jQuery comes in handy when you need to add or remove content from a web page upon request of user.

Adding or removing content is quite different to showing or hiding elements. Although, in most cases show/hide can do the job for you, its quite a different scenario when the elements are part of a form.

Hiding an element will not prevent values set in that element from being passed to the form data. Hence, removing element would be the correct procedure to follow.

Here' an example.

Lets assume we have a field to store social profile url.

<div class="form-group">
  <input type="url" name="social_profiles" class="form-control" placeholder="Enter Url">
</div>

Rather than asking the user to enter data in a specific way, so that, we could segregate each of them later, we would allow the user to add as many fields as he needs with a plus button. Hence, he can add individual url into individual fields.

<div id="socialFields">
  <div class="form-group">
    <input type="url" name="social_profiles[]" class="form-control" placeholder="Enter Url">
  </div>
</div>
<div class="text-right">
  <button class="btn btn-warning" id="addField"><i class="glyphicon glyphicon-plus"></i></button>
</div>	
	

Here, we changed the input field name to an array from string value, so that, we could take multiple values from same field. Now, we can add a jQuery script to add the same form element each time the button is clicked. We'll use jQuery append() method to add any html element inside an existing element.

<script>
$('#addField').click(function(){
  $('#socialFields').append('<div class="form-group"><input type="url" name="social_profiles[]" class="form-control" placeholder="Enter Url"></div>');
})
</script>	

If you wish to keep the total data count below a number, you can count the repetition of the wrapper div and prevent it from exceeding a limit.

<script>
$('#addField').click(function(){
  var count = $("#socialFields .form-group").length;
  if(count < 5){
    $('#socialFields').append('<div class="form-group"><input type="url" name="social_profiles[]" class="form-control" placeholder="Enter Url"></div>');
  }else{
    $("#socialFields").after('<div class="alert alert-danger"><strong>Sorry!</strong> you can only add 5 social profiles here.</div>');
  }
})
</script>

Here, if you check the result, the alert message appears everytime the button is clicked after 5 social fields are already in the page. To prevent the message from appearing, we can check if the message is already there.

Here, we used jQuery after() method to add html element after an existing html element. Similarly, we can use prepend() and before() to add elements before any existing html element.

<script> $('#addField').click(function(){ var count = $("#socialFields .form-group").length; if(count < 5){ $('#socialFields').append('<div class="form-group"><input type="url" name="social_profiles[]" class="form-control" placeholder="Enter Url"></div>'); }else{ var errorCount = $('.alert-social').length; if(errorCount == 0){ $("#socialFields").after('<div class="alert alert-danger alert-social"><strong>Sorry!</strong> you can only add 5 social profiles here.</div>'); } } }) </script>

All done then, lets see how we can remove those elements. First off all, we need to add a remove button to each of those input fields. And then, run a script to remove the ones we want.

Calling the class name directly in the script won't work for the element added via jQuery. So, we will need to call it use $(document).on('click', '.input-group-addon', function (){}). Then, either go for the chain as parent().parent('.form-group') or with closest() to find the closest parent form-group and remoev it.

<script>
$('#addField').click(function(){
  var count = $("#socialFields .form-group").length;
  if(count < 5){
    $('#socialFields').append('<div class="form-group"><div class="input-group"><input type="url" name="social_profiles[]" class="form-control" placeholder="Enter Url"><span class="input-group-addon"><i class="glyphicon glyphicon-minus"></i></span></div>');
  }else{
    var errorCount = $('.alert-social').length;
    if(errorCount == 0){
      $("#socialFields").after('<div class="alert alert-danger alert-social"><strong>Sorry!</strong> you can only add 5 social profiles here.</div>');
    }		
  }
})
$(document).on('click', '.input-group-addon', function () {
  // $(this).parent().parent('.form-group').remove(); 
  $(this).closest('.form-group').remove();
  // any of these two will work
});
</script>

Finally, you would like to remove the error message, in case the message is shown and the count reaches lower than the threshold.

So, here's your final piece of code to add or remove html input elements dynamically from your webpage.

<script>
$('#addField').click(function(){
  var count = $("#socialFields .form-group").length;
  if(count < 5){
    $('#socialFields').append('<div class="form-group"><div class="input-group"><input type="url" name="social_profiles[]" class="form-control" placeholder="Enter Url"><span class="input-group-addon"><i class="glyphicon glyphicon-minus"></i></span></div>');
  }else{
    var errorCount = $('.alert-social').length;
    if(errorCount == 0){
      $("#socialFields").after('<div class="alert alert-danger alert-social"><strong>Sorry!</strong> you can only add 5 social profiles here.</div>');
    }		
  }
})
$(document).on('click', '.input-group-addon', function () {
  $(this).closest('.form-group').remove();
  $('.alert-social').remove();
});
</script>

0 Like 0 Dislike 0 Comment Share

Leave a comment