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

Advertisements

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 🙁

<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="idesc">
  <input type='text' id='idesc_1' value='idesc_1'>
</div>

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

<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+"'>";

    $('#'+inpnam).append(new_input);
    $('#'+inpnum).val(new_id);
    }
}

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

  if(last_id>1){
    $('#'+inpnam+'_'+last_id).remove();
    $('#'+inpnum).val(last_id-1);
  }
}

$('#edadd').on('click', add('edinpt','edesc'));
$('#edrem').on('click', remove('edinpt','edesc'));
$('#idadd').on('click', add('idinpt','idesc'));
$('#idrem').on('click', remove('idinpt','idesc'));
</script>
</body>
</html>

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() {
    add('edinpt','edesc');
});
$('#edrem').on('click', function() {
    remove('edinpt','edesc');
});
$('#idadd').on('click', function() {
    add('idinpt','idesc');
});
$('#idrem').on('click', function() {
    remove('idinpt','idesc');
});

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 ReplyCancel reply