1

I'm creating an app to build your own form with JQuery. I want to add more options on the checkbox and the radio type questions. For some reason the last function isn't working. It's meant to add a new option when clicking on the button created in the first function.

//Adding a checkbox question
$("#addCheckboxQuestion").click( function(){
$("#rectangle").before("<br><input type='text'placeholder='Question'> <input type='checkbox'> <input type='text' placeholder='Opção'> <button class='btn newOption'>+</button>");
});

//Adding a new option
$(".newOption").click( function(){
console.log("+ radiobutton");
$(this).before("<input type='checkbox'> <input type='text' placeholder='Option'>");
});

I tried putting " onclick='' " directly on the button and do a normal javascript function and it worked fine. The problem with that is that if I have several checkbox type questions new options will only be added to the first question.

1
  • I Updated my answer I think now it solves your question. Commented May 27, 2018 at 20:56

1 Answer 1

0

Update: I think I understand your question now. Check out the new Code.

It is probably not a very beautiful solution but this should work.

Creating an element with jQuery, than attaching the event, than attaching the new element with the event onto the DOM.

I added some HTML so that the example can run here.

$("#btn1").click( function(){
var question = $("<div><input type='text'placeholder='Question'> <input  type='checkbox'> <input type='text' placeholder='Opção'><button class='btn newCheck'>Add Option</button></div>");

    $("#rectangle").before(question);
    
    $(question).find(".newCheck").click( function(){
      console.log("+ radiobutton");

      $(this).before("<input type='checkbox'> <input type='text' placeholder='Option'>");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">Add Question</button>
<div id="rectangle"></div>

2
  • It works great!! Sorry the question was a bit confusing. It was actually my first time posting here. Thank you :D
    – Alex
    Commented May 27, 2018 at 21:58
  • @Alex great to hear, could you than accept my answer. :-D Commented May 28, 2018 at 4:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.