0

I have a function addFrom which is triggered by a button. I would like to reuse changing the target ID and class. It works when I don't add any arguments. This is done using $(document).ready(function() as shown below, but when I try to use an argument it works only the first time I don't understand how can I use the function passing some arguments using $(document).ready.

function addForm(TF) {
  var $templateForm = $(TF);
  console.log($templateForm)
}

$(document).ready(function() {
  $('#add').click(addForm('#form2'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <a id="add" href="#">Add form</a>
</body>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
G M
  • 20,759
  • 10
  • 81
  • 84

2 Answers2

2

You need to wrap in a function

I would also use .on and prevent the default action

function addForm(TF) {
  const $templateForm = $(TF);
  console.log($templateForm)
}


$(document).ready(function() { // shorter: $(function() {
  $('#add').on('click',function(e) { 
    e.preventDefault(); // stop the link
    addForm('#form2');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="add" href="#">Add form</a>

<form id="form2"></form>

jQuery can help you though passing data, but I find it harder to read

function addForm(event) {
  event.preventDefault()
  const $templateForm = $(event.data.TF);
  console.log($templateForm)
}


$(function() {
  $('#add').on('click',{'TF':'#form2'},addForm)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="add" href="#">Add form</a>

<form id="form2"></form>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • `$(function() {` is the exact same as `$(document).ready(function() {` just shorter - see update – mplungjan Feb 25 '21 at 12:51
  • Also `$('#add').on('click',function(e) {` is a more versatile version of `$('#add').click(function(e) { ` – mplungjan Feb 25 '21 at 12:53
  • 1
    BTW, If you do `$("something").someEvent(somefunction())` where you have () on somefunction, the somefunction is executed immediately the browser sees the code – mplungjan Feb 25 '21 at 14:02
1
<script>
$(document).ready(function() {
  $("#add").click(function(){
    addForm('#form2');
  });
});
</script>

Hope It's Help You

Hiren Devganiya
  • 353
  • 1
  • 8