I am dynamically adding a SELECT element to a form, then submitting using JQuery Form Plugin for an ajax form submit. I want to (1) add the SELECT to the form, (2) place the SELECT inside a DIV and (3) submit the form using an ajax call properly. I can't seem to do all three!
<form name="mainForm" id="mainForm" method="POST" action="fellowRight.php">
...various working form elements
<div class="field_wrapper">
</div>
</form>
The code above is a snippet of a form in use. I then add some additional select elements dynamically as per below
$(addFormElementButton).click(function(){
var fieldHTML = '<select required name="ABC" ><option value="LT">Left</option><option selected value="RT">Right</option></select>';
$('.field_wrapper'); .append(fieldHTML); // Add field html
$('select[name=ABC]').appendTo('#mainForm');
}
The problem is that elements "appendto" the form, not the div ".field_wrapper" as intented (and therefore appear outside of the intended DIV). I can get it to format correctly if I omit the appendTo but then the select is no longer linked to the form.
If I omit the AppendTo code and instead I add a form="mainForm" call in the <select> element, it formats correctly and submits correctly. HOWEVER, then I get duplication of this specific SELECT element in my form data submitted via JQUERY FORM (.ajaxForm).
Is there a way to link the SELECT element to the form without using appendTo or form= or should I just forget about using Jquery Form
Just insert the
selectinside.field_wrapper, it's already inside the form.You may also want to cancel the click event on
addFormElementButton, because if it's abuttonit might be submitting the form automatically.