Html Form doesnt submit after append with jquery - javascript

I append HTML form with jquery append function but when I click on submit button it doesn't submit
$( "body" ).on( "click", "#addPackage", function() {
packageId = 'package'+ id;
id = id+1;
$('.table tbody').append('<tr id="' + packageId + '"> <form class="" onsubmit="editPackage();return false;" method="post"><td><input type="text" name="package_name" value="" /></td><td><input type="text" name="package_price" value="" /></td><td><input type="text" name="package_details" value="" /></td><td><button class="btn btn-success" ><i class="fa fa-save"></i></button> <span class="btn btn-danger remove-btn"><i class="fa fa-remove"></i></span></td></form></tr>');
});

This is what you probably want, instead of use <form> (which only execute function editPackage) in <tr> (and it is incorrect was what mentioned in Justinas comment ) you can execute editPackage after click on row-button and read data fro row in this way (i remove <form> from your append string and change <button>):
let id=0;
$( "body" ).on( "click", "#addPackage", function() {
packageId = 'package'+ id;
id = id+1;
//console.log($('.table tbody'));
$('.table tbody').append('<tr id="' + packageId + '"> <td><input type="text" name="package_name" value="" /></td><td><input type="text" name="package_price" value="" /></td><td><input type="text" name="package_details" value="" /></td><td><button class="btn btn-success" onclick="editPackage(this)">submit<i class="fa fa-save"></i></button> <span class="btn btn-danger remove-btn"><i class="fa fa-remove"></i></span></td></tr>');
});
function editPackage(btn) {
let tds =btn.parentNode.parentNode.children
let v1=tds[0].children[0].value;
let v2=tds[1].children[0].value;
let v3=tds[2].children[0].value;
console.log('submit', v1, v2, v3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="addPackage">add</button>
<table class="table"><tbody></tbody><table>

Related

How can I add an incrementing id="" attribute to the following JavaScript generated HTML form?

I have managed to come up with the following JavaScript and HTML but now I am stuck. I want to be able to add an id="" attribute to the fields and have them numbered as I add more fields with the '+ Add' button.
I've been playing around with this but have not had any success yet. Could someone give me some suggestions or offer some solutions to this issue?
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><table width="100%"><tr><td><input type="text"
name="field_name[]" value="" class="form-control" style="width:98%;"
placeholder="Role"/></td><td><input type="text" name="field_name[]" value=""
class="form-control" style="width:100%;" placeholder="Name"/></td></tr></table>
<a href="javascript:void(0);" class="remove_button"><button type="button"
class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> -
Remove </button></a></div>';
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
<label style="margin-top:70px;">Credits</label>
<div class="field_wrapper">
<div class="form-group">
<table width='100%'>
<tr>
<td>
<input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%"/>
</td>
<td>
<input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%"/>
</td>
</table>
<a href="javascript:void(0);" class="add_button" title="Add field">
<button style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role </button>
</a>
</div>
</div>
You can try this snippet:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
$(document).ready(function () {
var x = 1; //Initial field counter is 1
var idCounter = 0;
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
function fieldHTML(id) {
return '<div><table width="100%"><tr><td>id:' + id + '<input type="text"' +
'id="role-' + id + '" name = "field_name[]" value = "" class="form-control" style = "width:98%;"' +
'placeholder = "Role" /></td > <td><input type="text" id="name-' + id + '" name="field_name[]" value=""' +
'class="form-control" style="width:100%;" placeholder="Name" /></td></tr ></table >' +
'<a href="javascript:void(0);" class="remove_button"><button type="button"' +
'class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> - Remove </button></a></div >';
}
//Once add button is clicked
$(addButton).click(function () {
//Check maximum number of input fields
if (x < maxField) {
$(wrapper).append(fieldHTML(idCounter++)); //Add field html
x++; //Increment field counter
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<label style="margin-top:70px;">Credits</label>
<div class="field_wrapper">
<div class="form-group">
<table width='100%'>
<tr>
<td>
<input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%" />
</td>
<td>
<input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%" />
</td>
</table>
<a href="javascript:void(0);" class="add_button" title="Add field"><button
style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role
</button></a>
</div>
</div>
Note, I have created a new variable idCounter to keep the id unique even when you remove a row. Otherwise, it might create elements with duplicate ids.
This is just one quick way, but there are many other ways this can be achieved. The code can be made mode tidy and readable.

On click and cloning timepicker cannot able to work

Below is my code for cloning the timepicker.
I have tried to remove hasDatepicker class on click and tried to call timepicker again but its not working. Below is my code
$(document).ready(function() {
var clone_index = 0;
console.log(max_value);
$("#add_period_break").click(function() {
$(".start_time").removeClass('hasDatepicker');
$('.start_time').timepicker({});
clone_index = clone_index + 1;
//$("#countform").val(clone_index);
console.log("add" + clone_index);
$(this).parent().before($("#clone").clone().attr("id", "clone" + clone_index));
$("#clone" + clone_index).css("display", "inline");
$("#clone" + clone_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + clone_index);
$(this).attr("id", $(this).attr("id") + clone_index);
$("#countform").val(clone_index);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id='clone'>
<div class="form-group">
<label for="exampleInputEmail1">Start Time</label>
<input type="text" name="start_time" id="start_time" class="form-control start_time" readonly="readonly" value="" placeholder="Start Time">
</div>
</div>
<div id="box-footer">
<button type="button" class="btn btn-success" name="add_period_break" id="add_period_break"><i class="glyphicon glyphicon-plus"></i> Add Periods/ Breaks</button>
<button type="submit" class="btn btn-primary"> Submit</button>
</div>
You want to use jQuery timepicker
You don't need to remove hasDatepicker class, because its will never assigned to it.
Also there is a variable max_value which is not assigned. so please remove it.
Please check below code:
$(document).ready(function () {
var clone_index = 0;
$('.start_time').timepicker({});//For first time on page load
$("#add_period_break").click(function () {
clone_index = clone_index + 1;
$(this).parent().before($("#clone").clone().attr("id", "clone" + clone_index));
$("#clone" + clone_index).css("display", "inline");
$("#clone" + clone_index + " :input").each(function () {
$(this).attr("name", $(this).attr("name") + clone_index);
$(this).attr("id", $(this).attr("id") + clone_index);
$("#countform").val(clone_index);
});
$('.start_time').timepicker({});///to apply timepicker on newly added textbox
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.js"></script>
<div id='clone'>
<div class="form-group">
<label for="exampleInputEmail1">Start Time</label>
<input type="text" name="start_time" id="start_time" class="form-control start_time" readonly="readonly" value="" placeholder="Start Time">
</div>
</div>
<div id="box-footer">
<button type="button" class="btn btn-success" name="add_period_break" id="add_period_break"><i class="glyphicon glyphicon-plus"></i> Add Periods/ Breaks</button>
<button type="submit" class="btn btn-primary"> Submit</button>
</div>

Keyup not working for dynamically added input-groups

I have already gone through questions available on this topic and have tried everything, but still my keyup function is not working.
$(document).ready(function() {
$(document).on('keyup', '.pollOption', function() {
var empty = false;
$(".pollOption").each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$("#cpsubmit").attr('disabled', 'disabled');
$("#moreop").attr('disabled', 'disabled');
} else {
$("#cpsubmit").removeAttr('disabled');
$("#moreop").removeAttr('disabled');
}
});
//Keep Track of no. of options on the page
var noOfOptions = 2;
// Function to add input fields (since I may have to delete them I've use bootstrap's input-groups, I guess this is causing issue)
$("#moreop").on('click', function() {
noOfOptions++;
$("#options").append("<div class='input-group pollOption'><input class='form-control' type='text' placeholder='New Option' name='op" + noOfOptions + "'/><span class='input-group-addon'><a href='#' id='removeOption' class='text-danger'>Remove</a></span></div>");
});
// To delete any option (only the dynamically created options can be deleted)
$("#cpform").on('click', '#removeOption', function() {
$(this).parents('.input-group').remove();
noOfOptions--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="cpform" method="POST" action="/polls/add">
<div class="form-group">
<label>Title</label>
<input id="title" type="text" placeholder="Ask your question here..." name="title" class="form-control" />
</div>
<div id="options" class="form-group">
<label>Options</label>
<input type="text" placeholder="Option 1" name="op1" class="form-control pollOption" />
<input type="text" placeholder="Option 2" name="op2" class="form-control pollOption" />
</div>
<button id="moreop" type="button" disabled="disabled" class="btn btn-outline-info btn-primary">More Options</button><br/><br/>
<button id="cpsubmit" type="submit" disabled="disabled" class="btn btn-info btn-primary">Submit</button>
</form>
This code works perfectly for the two inputs already in the HTML part.
When I click on the "More Option" button the new field gets added but the "keyup" does not work on it. In fact, when I enter something on the new added inputs then my "More Option" & "Submit" button gets disabled (really do't know why this is happening).
You've to add the class pollOption to the input and not the div in your append :
$("#options").append("<div class='input-group'><input class='pollOption form-control' ...
_____________________________________________________________^^^^^^^^^^
Instead of :
$("#options").append("<div class='input-group pollOption'><input class='form-control' ...
______________________________________________^^^^^^^^^^
Demo:
$(document).ready(function() {
$(document).on('keyup', '.pollOption', function() {
var empty = false;
$(".pollOption").each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$("#cpsubmit").attr('disabled', 'disabled');
$("#moreop").attr('disabled', 'disabled');
} else {
$("#cpsubmit").removeAttr('disabled');
$("#moreop").removeAttr('disabled');
}
});
//Keep Track of no. of options on the page
var noOfOptions = 2;
// Function to add input fields (since I may have to delete them I've use bootstrap's input-groups, I guess this is causing issue)
$("#moreop").on('click', function() {
noOfOptions++;
$("#options").append("<div class='input-group'><input class='pollOption form-control' type='text' placeholder='New Option' name='op" + noOfOptions + "'/><span class='input-group-addon'><a href='#' id='removeOption' class='text-danger'>Remove</a></span></div>");
$(this).attr('disabled','disaled');
});
// To delete any option (only the dynamically created options can be deleted)
$("#cpform").on('click', '#removeOption', function() {
$(this).parents('.input-group').remove();
noOfOptions--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="cpform" method="POST" action="/polls/add">
<div class="form-group">
<label>Title</label>
<input id="title" type="text" placeholder="Ask your question here..." name="title" class="form-control" />
</div>
<div id="options" class="form-group">
<label>Options</label>
<input type="text" placeholder="Option 1" name="op1" class="form-control pollOption" />
<input type="text" placeholder="Option 2" name="op2" class="form-control pollOption" />
</div>
<button id="moreop" type="button" disabled="disabled" class="btn btn-outline-info btn-primary">More Options</button><br/><br/>
<button id="cpsubmit" type="submit" disabled="disabled" class="btn btn-info btn-primary">Submit</button>
</form>

Autocomplete on dynamically generated divs

I have problem with autocomplete on my dynamically generated divs
File 1 - Javascript file which on button click generate div with input fields
var inputHTML = '<div id="addProducts" class="col-md-2 form-group"><input type="text" class="form-control" placeholder="Identyfikator opony" name="tyreID[]" id="tyreID"><input type="text" class="tyreSize form-control" placeholder="Rozmiar" name="tyreSize[]" id="tyreSize" required><input type="text" class="tyreManufacturer form-control" placeholder="Producent" name="tyreManufacturer[]" id="tyreManufacturer" required><input type="text" class="tyreTread form-control" placeholder="Bieżnik" name="tyreTread[]" id="tyreTread" required><input type="text" class="form-control" placeholder="DOT" name="tyreDOT[]" id="tyreDOT"><input type="number" step="0.01" min="0" class="form-control price" placeholder="Cena za sztukę" name="tyrePricePiece[]" id="tyrePricePiece" required><button href="#" class="btn btn-danger btn-block remove_field"><span class="glyphicon glyphicon-remove"></span> Usuń</button><button type="button" class="btn btn-warning btn-block" id="clone"><span class="glyphicon glyphicon-duplicate"></span> Kopiuj</button></div>';
var inputHTML2 = '<div id="addProducts2" class="col-md-2 form-group"><input type="text" class="form-control" placeholder="Identyfikator felg" name="alloyID[]" id="alloyID"><input type="text" class="alloySize form-control" placeholder="Rozmiar" name="alloySize[]" id="alloySize" required><input type="text" class="alloyManufacturer form-control" placeholder="Producent" name="alloyManufacturer[]" id="alloyManufacturer" required><input type="text" class="alloyPCD form-control" placeholder="Rozstaw" name="alloyPCD[]" id="alloyPCD" required><input type="text" class="form-control" placeholder="Otwór centrujący" name="alloyHub[]" id="alloyHub"><input type="number" step="0.01" min="0" class="form-control price" placeholder="Cena za komplet" name="alloyPricePiece[]" id="alloyPricePiece" required><button href="#" class="btn btn-danger btn-block remove_field"><i class="fa fa-times"></i> Usuń</button><button type="button" class="btn btn-warning btn-block" id="clone"><span class="glyphicon glyphicon-duplicate"></span> Kopiuj</button></div>';
var addInput = function() {
$(inputHTML).appendTo('div#products');
};
var addInput2 = function() {
$(inputHTML2).appendTo('div#products');
};
var cloneInput = function() {
$(this).appendTo('div#products');
}
$('button#btnAddProduct').click(addInput);
$('button#btnAddProduct2').click(addInput2);
$(document).on('click', '.remove_field', function(e) { //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(0);
sumPrice();
});
$(cloneInput).on('click', '#clone', function(e) {
e.preventDefault();
$(this).parent('#addProducts').each(function() {
$(this).clone().appendTo('div#products').val($(this).val());
});
sumPrice();
});
$(cloneInput).on('click', '#clone', function(e) {
e.preventDefault();
$(this).parent('#addProducts2').each(function() {
$(this).clone().appendTo('div#products').val($(this).val());
});
sumPrice();
});
File 2 - Javascript file which makes autocomplete working
var ac_config2 = {
source: "../../libs/orders/autocomplete_products.php",
select: function(event, ui){
$("#tyreID").val(ui.item.id_product);
$("#tyreSize").val(ui.item.Szerokosc+"/"+ui.item.Profil+"R"+ui.item.Srednica);
$("#tyreManufacturer").val(ui.item.Producent);
$("#tyreTread").val(ui.item.Model);
$("#tyreDOT").val(ui.item.DOT);
//$("#tyrePricePiece").val(ui.item.client_name);
},
minLength: 1
};
$("#tyreID").autocomplete(ac_config2);
If I add productbox to html file autocomplete works great, but at dynamically generated div it not works at all.
How can i reload this autocomplete file on each div add? Or there is another way of this?
Still got problem with 1 thing. If I setup it to #div id it copies values always to first div, if to .div class it copies values to all divs.
#Justas?

Creating a quiz using php, To store array data in a field in the database

I'm trying to create a dynamic quiz and store it in database, the inputs is composed of 1 question and 4 answers.
I made the textbox and radio buttons dynamically created using jquery. The 1 textbox is for the question and the other 4 textbox is for the answer, I have also 4 radio buttons for correct answer.
var ctr = 2;
$("#addTextBox").click(function() {
var newTBdiv = $(document.createElement('div'))
.attr("id", 'QuestionTBDiv' +ctr);
newTBdiv.css({"margin-top":"20px" });
newTBdiv.css({"width":"500px"});
newTBdiv.css({"padding":"5px"});
newTBdiv.after().html('<label class="mlabel">Question</label><br/><input type="text" name="quiztxtBox'+ctr+'" size="57" id="quiztxtBox'+ctr+'" placeholder="Question #'+ctr+'"><br/><label class="mlabel">Answer</label><br/><input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice A"> <input type="radio" name="correct_answer'+ctr+'" value="A"> <input type="text" name="answer'+ctr+'" size="24" id="answer'+ctr+'" placeholder="Choice B">&nbsp<input type="radio" name="correct_answer'+ctr+'" value="B"><br/><input type="text" name="answer'+ctr+'" size="24" id="answer'+ctr+'" placeholder="Choice C"> <input type="radio" class = "choiceC" name="correct_answer'+ctr+'" value="C"> <input type="text" name="answer'+ctr+'"size="24" id="answer'+ctr+'" placeholder="Choice D"> <input type="radio" name="correct_answer'+ctr+'" value="D"><br><span name="errMchoice" class="errorMsg"></span>')
newTBdiv.appendTo("#exam_container");
ctr++;
});
Now the problem is, I need to store the data of questions and answer to one field only in the database.. I found out that using serialize() function will able to store the array in the field, But Im not quite sure of what I am doing. I was thinking of something like this. This is the array that I was thinking to serialize and store in the database.
$array = array(
array(question1, answer1, answer2, answer3, answer4, correctanswer);
array(question1, answer1, answer2, answer3, answer4, correctanswer);
);
Or is there other method to achieve this?
What you do is update you would use 2 tables to be like this:
table: Quizes
id, title, creator, etc
table: Quiz_Settings
id //(simply for managing rows and edits/updates)
"1", "2", "3" // etc
quiz_id
"55912" // or so on
type
"question", "answer"
ref_number
"1", "2" // This is basically Question 1, Question 2, Answer 1 etc.
value
"What is ...?" or "21" // The question or the answer
You would then get quiz by id = 55912, and check against quiz settings for all with "quiz_id" == 55912, and using the "question" field and "ref_number" field, you generate a table or page which has the questions, and then a field which has to be equal to "answer" "1"
In the event of MULTIPLE answers, you simply loop through each "answer" "1", if it's correct, +1, if it's incorrect, 0.
// EXAMPLE JS:
<script>
var num_fields = <?=($num_fields > 0 ? $num_fields : 0)?>;
var num_multi_fields = <?=($num_multi_fields > 0 ? $num_multi_fields : 0)?>;
var cf = new Array();
var cv = new Array();
<?for($i=1;$i<=$num_fields;$i++) { ?>cf[<?=$i?>] = "<?=${'cf'.$i}?>"; cv[<?=$i?>] = "<?=${'cv'.$i}?>";<? } ?>
var cmf = new Array();
<?for($i=1;$i<=$num_multi_fields;$i++) { ?>
cmf[<?=$i?>] = "<?=${"cmf".$i}?>";
var cmv<?=$i?> = new Array();
<?$k = 0; for($j=1;$j<=${"cmf".$i."vt"};$j++) {?>
cmv<?=$i?>[<?=$k?>] = "<?=${"cmf".$i."v".$j}?>";
<? $k++; } ?>
<?} ?>
$(document).ready(function() {
$("#num_fields").val(num_fields);
for(i=1;i<=num_fields;i++) {
$("#custom_fields").append(
'<div id="custom_'+i+'"><br/><label for="custom_field_'+i+'" class="custom-label">Custom Field '+i+': </label> '
+ '<button type="button" class="btn btn-xs btn-danger delete_custom_o">Delete</button><br />'
+ '<table width="100%"><tr><td>Field Name:</td><td>Field Value:</td></tr><tr>'
+ '<td><input type="text" class="form-control custom_field" value="'+cf[i]+'" name="custom_field_'+i+'"/></td>'
+ '<td><input type="text" class="form-control custom_value" value="'+cv[i]+'" name="custom_value_'+i+'"/></td></tr></table></div>'
);
};
$(".delete_custom_o").click(function() {
$(this).parent().remove();
var i = 0;
$("#custom_fields>div").each(function() {
i++;
$(this).find('label').text("Custom Field " +i+":");
$(this).find('.custom_field').attr("name", "custom_field_"+i);
$(this).find('.custom_value').attr("name", "custom_value_"+i);
});
num_fields--;
$("#num_fields").val(num_fields);
});
});
$("#add_field").click(function() {
num_fields++;
$("#num_fields").val(num_fields);
$("#custom_fields").append(
'<div id="custom_'+num_fields+'"><br/><label for="custom_field_'+num_fields+'">Custom Field '+num_fields+':</label> '
+ '<button type="button" class="btn btn-xs btn-danger delete_custom_n">Delete</button><br />'
+ '<table width="100%"><tr><td>Field Name:</td><td>Field Value:</td></tr><tr>'
+ '<td><input type="text" class="form-control custom_field" name="custom_field_'+num_fields+'"/></td>'
+ '<td><input type="text" class="form-control custom_value" name="custom_value_'+num_fields+'"/></td></tr></table></div>'
);
});
$('#custom_fields').on("click", ".delete_custom_n", function(){
$(this).parent().remove();
var i = 0;
$("#custom_fields>div").each(function() {
i++;
$(this).find('label').text("Custom Field " +i+":");
$(this).find('.custom_field').attr("name", "custom_field_"+i);
$(this).find('.custom_value').attr("name", "custom_value_"+i);
});
num_fields--;
$("#num_fields").val(num_fields);
});
$("#add_multi_field").click(function() {
num_multi_fields++;
$("#num_multi_fields").val(num_multi_fields);
$("#custom_multi_fields").append(
'<div id="custom_'+num_multi_fields+'" style="border-bottom: 1px solid #ddd; padding-bottom: 5px;"><br/>'
+ '<label for="custom_field_'+num_multi_fields+'">Custom Field '+num_multi_fields+':</label> '
+ '<button type="button" class="btn btn-xs em-bg-blue add_custom_n" data-id="'+num_multi_fields+'" data-target="#custom_table_'+num_multi_fields+'">Add</button> '
+ '<button type="button" class="btn btn-xs btn-danger delete_custom_n">Delete</button><br />'
+ '<div style="max-height:100px; overflow-y:auto; padding-left: 10px; padding-right: 10px;"><table width="100%" id="custom_table_'+num_multi_fields+'"><tr><td>Field Name:</td><td>Field Value:</td></tr><tr>'
+ '<td><input type="text" class="form-control custom_field" name="custom_multi_field_'+num_multi_fields+'"/></td>'
+ '<td><input type="text" class="form-control custom_value" name="custom_multi_value_'+num_multi_fields+'[]"/></td></tr>'
+ '<tr><td><center><button type="button" class="btn btn-xs btn-danger delete_field">Remove</button></center></td>'
+ '<td><input type="text" class="form-control custom_value" name="custom_multi_value_'+num_multi_fields+'[]"/></td></tr></table></div></div>'
);
});
$('#custom_multi_fields').on("click", ".add_custom_n", function(){
target = $(this).attr('data-target');
id = $(this).attr('data-id');
$(target).find('tbody')
.append($('<tr>')
.append($('<td>').html('<center><button type="button" class="btn btn-xs btn-danger delete_field">Remove</button></center>'))
.append($('<td>')
.append($('<input>').attr('type', 'text').attr('class', 'form-control custom_value').attr('name', 'custom_multi_value_'+id+'[]'))
)
);
});
$('#custom_multi_fields').on("click", ".delete_field", function(){
$(this).parent().parent().parent().remove();
});
$('#custom_multi_fields').on("click", ".delete_custom_n", function(){
$(this).parent().remove();
var i = 0;
$("#custom_multi_fields>div").each(function() {
i++;
$(this).find('label').attr('for','custom_field_'+i).text("Custom Field " +i+":");
$(this).attr('id','custom_'+i);
$(this).find('button.add_custom_n').attr('data-target', '#custom_table_'+i).attr('data-id', i);
$(this).find('table').attr("id","custom_table_"+i);
$(this).find('.custom_field').attr("name","custom_multi_field_"+i);
$(this).find('.custom_value').attr("name","custom_multi_value_"+i+"[]");
});
num_multi_fields--;
$("#num_multi_fields").val(num_multi_fields);
});
$(document).ready(function() {
$("#num_multi_fields").val(num_multi_fields);
for(i=1;i<=num_multi_fields;i++) {
var curr_array = window['cmv' + i];
string = "";
for(j=1;j<curr_array.length;j++) {
string += '<tr><td><center><button type="button" class="btn btn-xs btn-danger delete_field">Remove</button></center></td>'
+ '<td><input type="text" class="form-control custom_value" value="'+curr_array[j]+'" name="custom_multi_value_'+i+'[]"/></td></tr>'
}
$("#custom_multi_fields").append(
'<div id="custom_'+i+'" style="border-bottom: 1px solid #ddd; padding-bottom: 5px;"><br/>'
+ '<label for="custom_field_'+i+'">Custom Field '+i+':</label> '
+ '<button type="button" class="btn btn-xs em-bg-blue add_custom_n" data-id="'+i+'" data-target="#custom_table_'+i+'">Add</button> '
+ '<button type="button" class="btn btn-xs btn-danger delete_custom_n">Delete</button><br />'
+ '<div style="max-height:100px; overflow-y:auto; padding-left: 10px; padding-right: 10px;"><table width="100%" id="custom_table_'+i+'"><tr><td>Field Name:</td><td>Field Value:</td></tr></tr>'
+ '<td><input type="text" class="form-control custom_field" value="'+cmf[i]+'" name="custom_multi_field_'+i+'"/></td>'
+ '<td><input type="text" class="form-control custom_value" value="'+curr_array[0]+'" name="custom_multi_value_'+i+'[]"/></td></tr>'
+ ""+string+""
+ '</table></div></div>'
);
};
$(".delete_custom_o").click(function() {
$(this).parent().remove();
var i = 0;
$("#custom_multi_fields>div").each(function() {
i++;
$(this).find('label').attr('for','custom_field_'+i).text("Custom Field " +i+":");
$(this).attr('id','custom_'+i);
$(this).find('button.add_custom_n').attr('data-target', '#custom_table_'+i).attr('data-id', i);
$(this).find('table').attr("id","custom_table_"+i);
$(this).find('.custom_field').attr("name","custom_multi_field_"+i);
$(this).find('.custom_value').attr("name","custom_multi_value_"+i+"[]");
});
num_multi_fields--;
$("#num_multi_fields").val(num_multi_fields);
});
$(".delete_field").click(function() {
$(this).parent().parent().parent().remove();
});
});
</script>
The Example HTML: Custom Field = 1 to 1 relationship (1 question 1 answer) - Multi Field = 1 to many relationship (1 question multiple answers)
<div class="row">
<div class="col-lg-6">
<button type="button" class="btn em-bg-blue" id="add_field">Add Custom Field</button><br />
<div id="custom_fields" style="max-height: 500px; overflow-y: auto;"></div>
</div>
<div class="col-lg-6">
<button type="button" class="btn em-bg-blue" id="add_multi_field">Add Multi Field</button><br />
<div id="custom_multi_fields" style="max-height: 500px; overflow-y: auto;"></div>
</div>
</div>
Serialization is an alright method. Have a look at the jQuery library, or try to write a very simple PHP file that will serialize for you.

Categories