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>

0

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

$(function() { is the exact same as $(document).ready(function() { just shorter - see update
Also $('#add').on('click',function(e) { is a more versatile version of $('#add').click(function(e) {
BTW, If you do $("something").someEvent(somefunction()) where you have () on somefunction, the somefunction is executed immediately the browser sees the code
1
<script>
$(document).ready(function() {
  $("#add").click(function(){
    addForm('#form2');
  });
});
</script>

Hope It's Help You

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.