How can I remove an element from a form using its ID in JQuery?

Hello and happy new year to everyone :D.

I am currently trying to develop a way to add and delete an input from a form using javascript and jquery.

The problem is i am not familiarized with declaring functions on jquery so I beg for your help because I currently ran out of ideas.

I currently have this.

So the idea is to have 4 buttons in the bottom. Two for add or delete extra inputs for percentages "A", and the other pair to add or delete extra inputs for percentages "B".

I was trying to do it the easy way by declaring four independent functions (i.e addA, removeA, addB, removeB), but i want to achieve this in a few lines. So that’s why i opted to declare it as a function with two input parameters. Since i did that the code doesn’t work anymore 🙁

<script src=""></script>
<div id="idesc">
  <input type='text' id='idesc_1' value='idesc_1'>

<div id="edesc">
  <input type='text' id='edesc_1' value='edesc_1'>

<input type="hidden" value="1" id="idinpt">
<input type="hidden" value="1" id="edinpt">

<button id="idadd">Add input for data A</button><button id="idrem">Remove input for data A</button>
<button id="edadd">Add input for data B</button><button id="edrem">Remove input for data B</button>

<script type="text/javascript">
function add(inpnum, inpnam){
    var act_id = parseInt($('#'+inpnum).val());
  if(act_id<5){ //5 input
    var new_id = act_id+1;
    var new_input = "<input type='text' id='"+inpnam+"_"+new_id+"' value='"+inpnam+"_"+new_id+"'>";


function remove(inpnum, inpnam){
    var last_id = $('#'+inpnum).val();


$('#edadd').on('click', add('edinpt','edesc'));
$('#edrem').on('click', remove('edinpt','edesc'));
$('#idadd').on('click', add('idinpt','idesc'));
$('#idrem').on('click', remove('idinpt','idesc'));

Thank you so much!

>Solution :

It looks like the problem is with the way you are calling the add and remove functions in the click handlers. Currently, you are calling the functions immediately and passing their return value to the on method, rather than passing a reference to the function itself.

To fix this, you can wrap the function calls in an anonymous function like this:

$('#edadd').on('click', function() {
$('#edrem').on('click', function() {
$('#idadd').on('click', function() {
$('#idrem').on('click', function() {

This way, the anonymous function will be called when the button is clicked, and the add or remove function will be called with the appropriate arguments.

Leave a Reply