Setting a dropdown selected value when generating a html table using jquery - javascript

I am generating a html table with a dropdown and a textbox from an array. I am storing array value property value in textbox and based on the value comin in the key property I want to to set the selected value of the dropdown in each row.
How can I set the dropdown value.
My code is like this. Everything is done I want only to set dropdown selected value.
var filtrnode=[arrayvalue];
$.each(filterNodeData.FilterData, function (i, item) {
debugger;
var newData = filterNodeData.FilterData[i];
trHTML += '<tr><td>' + '<select class="form-control"><option value="and">And</option><option value="or">Or</option></select>' + '</td>' +
'<td>' + '<input class="form-control" size=35 type="text" id="filterValue" value= ' + filterNodeData.FilterData[i].value + '>' + '</td>' +
'<td><input type="button" id="delFilter" class="delHeader btn btn-md red" value="Delete" onclick="deleteFilter(this)" ></td>' +
'<td><input type="button" id="AddFilter" class="btn btn-md btn-primary" value="Add" onclick="insertFilter()" ></td>' + '</tr>';
});
$('#filterTable').append(trHTML);
Thanks

You can set it by getting the option selected for that index like,
$.each(filterNodeData.FilterData, function (i, item) {
var newData = filterNodeData.FilterData[i],
value=newData.value,
key = newData.key;
trHTML += '<tr><td>' + '<select class="form-control">'+
'<option value="and" '+(key=='and'?'selected':'')+'>And</option>'+
'<option value="or" '+(key=='or'?'selected':'')+'>Or</option>'+
'</select></td>' +
'<td>' + '<input class="form-control" size=35 type="text" id="filterValue" value= ' + value + '>' + '</td>' +
'<td><input type="button" id="delFilter" class="delHeader btn btn-md red" value="Delete" onclick="deleteFilter(this)" ></td>' +
'<td><input type="button" id="AddFilter" class="btn btn-md btn-primary" value="Add" onclick="insertFilter()" ></td>' + '</tr>';
});
$('#filterTable').append(trHTML);

I would do it like this:
$(document).ready(function() {
// store your html as a variable, `` alows you to use lines in string
var row = `
<tr>
<td><select class="form-control"><option value="and">And</option><option value="or">Or</option></select></td>
<td><input class="form-control" size=35 type="text" id="filterValue"></td>
<td><input type="button" id="delFilter" class="delHeader btn btn-md red" value="Delete" onclick="deleteFilter(this)" ></td>
<td><input type="button" id="AddFilter" class="btn btn-md btn-primary" value="Add" onclick="insertFilter()" ></td>
</tr>
`
var filtrnode = [{arrayvalue}];
$.each(filtrnode, function(i, item) {
// make a jQuery object from your html variable
var newRow = $(row);
// and now you are free to use jQuery selectors and functions on it
newRow.find("select option[value="+ item.key +"]").prop("selected", true);
newRow.find("input[type='text']").val(item.value);
$('#filterTable').append(newRow);
});
});
Storing your HTML code as a variable using `` allows you tu use line breaks and create a code which is easier to read. After you create a jQuery object from your stored HTML you can access all of jQuery functions which is cool. This makes your code less prone to mistakes and typos. Here is a jsFiddle.

Related

How to use datalist inside dynamic table?

I am making dynamic table with adding rows and every row have datalist. The problem is that on first row it shows text, but on other rows it shows integer from Value. And I want to show text from data-text.
Check my code on: https://codepen.io/aleksandar095/pen/eYmqYVO
Maybe I still don't get it how id works. Problem might be in js code.
$(document).ready(function() {
var counter = 2;
$("#addrow").on("click", function() {
counter = $('#myTable tr').length - 2;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input list="animals" class="form-control" id="animal'+counter+'" name="animal"><datalist id="animals"><option data-text="cat" value="1">Text 1</option><option data-text="dog" value="2">Text 2</option><option data-text="fish" value="3">Text 3</option></datalist></td>';
cols += '<td><button type="button" class="ibtnDel btn btn-md btn-danger"><i class="fa fa-trash" style="color: #fff;"></i></button></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
$("#animal" + counter).bind("select", function() {
if ($('#animals').find('option').length) {
if ($('option[value=' + this.value + ']').length > 0) {
$("#animal" + counter).val($('option[value=' + this.value + ']').data("text"));
}
}
})
counter++;
});
Please check my full code on codepen.
Just changing these lines should help you output your contructed html.
var newRow = '<tr>'
var cols = '<td><input list="animals" class="form-control" id="animal'+counter+'" name="animal"><datalist id="animals"><option data-text="cat" value="1">Text 1</option><option data-text="dog" value="2">Text 2</option><option data-text="fish" value="3">Text 3</option></datalist></td>';
cols += '<td><button type="button" class="ibtnDel btn btn-md btn-danger"><i class="fa fa-trash" style="color: #fff;"></i></button></td>';
newRow += cols;
$("table.order-list").append(newRow);
Or, even simpler:
let newRow = '<tr>'
newRow += '<td><input list="animals" class="form-control" id="animal'+counter+'" name="animal"><datalist id="animals"><option data-text="cat" value="1">Text 1</option><option data-text="dog" value="2">Text 2</option><option data-text="fish" value="3">Text 3</option></datalist></td>';
newRow += '<td><button type="button" class="ibtnDel btn btn-md btn-danger"><i class="fa fa-trash" style="color: #fff;"></i></button></td>';
$("table.order-list").append(newRow);

Value of input text is empty after appending using jQuery

I am dynamically generating a form using AJAX and on the click of a button I add more input fields. But when I enter values in the input field and inspect in developer console,I don't see any value in the input text box.
Code for generating the form
$.ajax({
method: 'GET',
url: 'api/PayrollSystem/GetEmployeeSalaryAmount?AdminId=' + 1,
success: function(data) {
if (Object.keys(data).length == 0) {
$.alert({
title: 'Saved',
content: 'Account Number Saved!',
});
var row = ('<tr ><td colspan="3" text-align="center"> <b>No Registered Users</b></td></tr>');
$('.EmpTable').append(row);
} else {
$.each(data, function(index, value) {
var rows = ('<div id="form_div"><form method="post"><table class="table table-hover employee_table' + index + ' " align=center><thead><tr><td><b>Employee</td> <td><b>Amount</td></tr></thead><tbody><tr><td><b>' + value.FullName + '</b></td><td><input type="hidden" class="form-control Leavename" name="Leavename[]" value="Basic" placeholder="Enter Leave Name"> <input readonly class="form-control LeaveAmount" type="number" name="LeaveAmount[]" value=' + value.SalaryAmount + ' /><input class="form-control EmpId" type="hidden" name="Id[]" value=' + value.Id + ' /></td></tr><tr id="row' + index + 1 + '"><td><input type="text" class="form-control Leavename" name="Leavename[]" placeholder="Enter Leave Name"> </td><td> <input type="number" class="form-control LeaveAmount" name="LeaveAmount[]" placeholder="Enter Leave Amount"></td> </tr></tbody> </table> <input type="button" class="btn btn-success addRow" onclick="add_row(' + index + '); " value=" + Add More Payroll Item"></form> </div><hr />');
$('.EmpTable').append(rows);
});
}
}
});
Code for appending the row containing the new text box to the form
function add_row(index) {
$rowno = $(".employee_table tr").length;
$rowno = $rowno + 1;
$(".employee_table" + index + " tr:last").after("<tr id= 'row" + $rowno + "' > <td><input type='text' class='form-control Leavename' name='Leavename[]' placeholder='Enter Leave Name'> </td><td> <input type='number' name='LeaveAmount[]' class='form-control LeaveAmount' placeholder='Enter Leave Amount'></td><td> <input type='button' value='x' onclick=delete_row('row" + $rowno + "') ><br></td></tr>");
}
Immediate help will be well appreciated.
EDIT: My loop logic that gave no value when looping through the text boxes of each form generated.
$('#saveAdj').click(function() {
$('form').each(function() {
var thisForm = this;
alert($('.EmpId', thisForm).val());
alert($('.Leavename', thisForm).val());
alert($('.LeaveAmount', thisForm).val());
});
})

How to delete a hidden input added by jQuery

I'm trying to create a list of products added from a select in a form using jQuery.
After the addition of those products, I would like to send them with the rest of the form.
The question is when I delete a product, I would also like to remove the hidden input created before.
Could you someone please give me a hand.
Thanks!!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form-receta" id="form-receta">
<label for="nombre_receta">Nombre :</label><input id="nombre_receta" name="name_receta" type="text">
<label for="nombre_ingr">Ingredientes:</label><br />
<select style="width:7.7em;display: inline-block;" id="nombre_ingr" name="nombre_ingr">
<option></option>
<option value="1*Prueba">Prueba</option>
<option value="2*Test">Test</option>
</select>
<input id="cantidad_ingr" name="cantidad_ingr" placeholder="cantidad" type="text">
<input id="um_ingr" name="um_ingr" placeholder="U.M" type="text">
<button type="button" class="add-row">ADD</button>
<h3>Ingredientes</h3>
<table>
<tr >
<th>#</th>
<th></th>
<th>Cantidad</th>
<th>U.M</th>
<th>Eliminar</th>
</tr>
<tbody id="tabla-ingr"></tbody>
</table>
<script>
$(document).ready(function(){
var x = 0;
$(".add-row").click(function(){
var id_nombre = $("#nombre_ingr").val();
var res = id_nombre.split("*");
var nombre = res[1];
var id = res[0];
var cantidad = $("#cantidad_ingr").val();
var um = $("#um_ingr").val();
x = x + 1;
var markup = "<tr><td>" + x + "</td><td>" + nombre + "</td><td class=\"text-center\">" + cantidad +
"</td><td class=\"text-center\">" + um + "</td><td class=\"text-center\"><button type=\"button\" class=\"btn btn-xs btn-danger removebutton\"><span class=\"glyphicon glyphicon-remove\"></span>DEL</button></tr>";
$("tbody#tabla-ingr").append(markup);
$('#form-receta').prepend('<input type="hidden" name="_id_ingr[]" value="'+ id +'" />');
$('#form-receta').prepend('<input type="hidden" name="_cantidad_ingr[]" value="'+ cantidad +'" />');
$('#form-receta').prepend('<input type="hidden" name="_um_ingr[]" value="'+ um +'" />');
});
$(document).on('click', 'button.removebutton', function () {
$(this).closest('tr').remove();
return false;
});
});
</script>
Thanks!
You can set an id to those input hidden elements. Then, when you delete the row, you can look for the id of that specific row and delete only the input hidden related to that row.
I hope it makes sense!
$(document).ready(function(){
var x = 0;
$(".add-row").click(function(){
var id_nombre = $("#nombre_ingr").val();
var res = id_nombre.split("*");
var nombre = res[1];
var id = res[0];
var cantidad = $("#cantidad_ingr").val();
var um = $("#um_ingr").val();
x = x + 1;
var markup = "<tr><td>" + x + "</td><td>" + nombre + "</td><td class=\"text-center\">" + cantidad +
"</td><td class=\"text-center\">" + um + "</td><td class=\"text-center\"><button type=\"button\" class=\"btn btn-xs btn-danger removebutton\"><span class=\"glyphicon glyphicon-remove\"></span>DEL</button></tr>";
$("tbody#tabla-ingr").append(markup);
$('#form-receta').prepend('<input type="hidden" name="_id_ingr[]" id="_id_ingr_'+x+'" value="'+ id +'" />');
$('#form-receta').prepend('<input type="hidden" name="_cantidad_ingr[]" id="_cantidad_ingr_'+x+'" value="'+ cantidad +'" />');
$('#form-receta').prepend('<input type="hidden" name="_um_ingr[]" id="_um_ingr_'+x+'" value="'+ um +'" />');
});
$(document).on('click', 'button.removebutton', function () {
var ingrediente_row = $(this).closest('tr');
var ingrediente_id = $(ingrediente_row).children('td')[0].innerHTML;
$('#_id_ingr_' + ingrediente_id).remove();
$('#_cantidad_ingr_' + ingrediente_id).remove();
$('#_um_ingr_' + ingrediente_id).remove();
$(ingrediente_row).remove();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form-receta" id="form-receta">
<label for="nombre_receta">Nombre :</label><input id="nombre_receta" name="name_receta" type="text">
<label for="nombre_ingr">Ingredientes:</label><br />
<select style="width:7.7em;display: inline-block;" id="nombre_ingr" name="nombre_ingr">
<option></option>
<option value="1*Prueba">Prueba</option>
<option value="2*Test">Test</option>
</select>
<input id="cantidad_ingr" name="cantidad_ingr" placeholder="cantidad" type="text">
<input id="um_ingr" name="um_ingr" placeholder="U.M" type="text">
<button type="button" class="add-row">ADD</button>
</form>
<h3>Ingredientes</h3>
<table>
<tr >
<th>#</th>
<th></th>
<th>Cantidad</th>
<th>U.M</th>
<th>Eliminar</th>
</tr>
<tbody id="tabla-ingr"></tbody>
</table>
Simply add a specific class for each hidden field and and pass this no to delete button :
$(document).ready(function(){
var x=0;
$(".add-row").click(function(){
var id_nombre = $("#nombre_ingr").val();
var res = id_nombre.split("*");
var nombre = res[1];
var id = res[0];
var cantidad = $("#cantidad_ingr").val();
var um = $("#um_ingr").val();
x = x + 1;
var markup = "<tr><td>" + x + "</td><td>" + nombre + "</td><td class=\"text-center\">" + cantidad +
"</td><td class=\"text-center\">" + um + "</td><td class=\"text-center\"><button type=\"button\" class=\"btn btn-xs btn-danger removebutton\" data-id='"+x+"'><span class=\"glyphicon glyphicon-remove\"></span>DEL</button></tr>";
$("tbody#tabla-ingr").append(markup);
$('#form-receta').prepend('<input type="hidden" name="_id_ingr[]" class="_hidden_'+x+'" value="'+ id +'" />');
$('#form-receta').prepend('<input type="hidden" name="_cantidad_ingr[]" class="_hidden_'+x+'" value="'+ cantidad +'" />');
$('#form-receta').prepend('<input type="hidden" name="_um_ingr[]" class="_hidden_'+x+'" value="'+ um +'" />');
});
$(document).on('click', 'button.removebutton', function () {
$('._hidden_'+$(this).data('id')).remove();
$(this).closest('tr').remove();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form-receta" id="form-receta">
<label for="nombre_receta">Nombre :</label><input id="nombre_receta" name="name_receta" type="text">
<label for="nombre_ingr">Ingredientes:</label><br />
<select style="width:7.7em;display: inline-block;" id="nombre_ingr" name="nombre_ingr">
<option></option>
<option value="1*Prueba">Prueba</option>
<option value="2*Test">Test</option>
</select>
<input id="cantidad_ingr" name="cantidad_ingr" placeholder="cantidad" type="text">
<input id="um_ingr" name="um_ingr" placeholder="U.M" type="text">
<button type="button" class="add-row">ADD</button>
</form>
<h3>Ingredientes</h3>
<table>
<tr>
<th>#</th>
<th></th>
<th>Cantidad</th>
<th>U.M</th>
<th>Eliminar</th>
</tr>
<tbody id="tabla-ingr"></tbody>
</table>
you can just use Jquery selected type=hidden to remove too, while you click remove botton.
$(document).on('click', 'button.removebutton', function () {
$(this).closest('tr').remove();
$('[type=hidden]').remove();
return false;
});
You can use input[type="hidden"] to remove input elements alone.
Code snippets:
$(document).on('click', 'button.removebutton', function () {
$(this).closest('tr').remove();
$('#form-receta input[type="hidden"]').remove();
return false;
});
Fiddle Demo
If the hidden inputs were added using append(), the order of these inputs woud be the same as shown in the table.
So there is 3 hidden fields created on each ADD click.
On DEL click, we know on wich row the click occured.
So we can deduct the index of the 3 hidden fields to remove.
In your HTML, I added <div id="hiddenInputList"></div> in the form.
Then in the code, to append the hidden fields:
// Append the hidden fields to a div, in the same order as the table.
$('#hiddenInputList').append('<input type="hidden" name="_id_ingr[]" value="'+ id +'" />');
$('#hiddenInputList').append('<input type="hidden" name="_cantidad_ingr[]" value="'+ cantidad +'" />');
$('#hiddenInputList').append('<input type="hidden" name="_um_ingr[]" value="'+ um +'" />');
And then, to remove them:
$(document).on('click', 'button.removebutton', function () {
var thisTR = $(this).closest("tr");
var thisTR_Index = thisTR.index();
console.log("thisTR_Index: "+thisTR_Index);
// Delete the 3 hidden fields (Must do it in the revers order)
$('#hiddenInputList').find("[type='hidden']").eq((thisTR_Index*3)+2).remove();
$('#hiddenInputList').find("[type='hidden']").eq((thisTR_Index*3)+1).remove();
$('#hiddenInputList').find("[type='hidden']").eq(thisTR_Index*3).remove();
// Remove the table row.
thisTR.remove();
return false;
});
In this CodePen, to be make it a visual example... Instead of hidden fields, I used classes.
Added fields are green. And on DEL click, we can see that re right ones are targeted because they turn red.

Can not keep id serially of textbox using Javascript/Jquery

I have an issue.I am adding multiple textbox using + button and deleting using - button. Here i am unable to keep each textbox's id serially. I am explaining my code below.
<div class="form-group" id="intro-box">
<input type="text" style="width:85%;float:left;margin-bottom:5px;" class="form-control" id="introlabelname0" name="introlabelname" placeholder="Label Name" value="">
<input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(1);">
</div>
<script>
var a = 0;
function addMore(i) {
a = a + 1;
i = a;
$("#plus").remove();
$('#intro-box').append('<div><input type="text" style="width:85%;float:left; margin-bottom:5px;" class="form-control" id="introlabelname' + i + '" name="introlabelname" placeholder="Label Name" value="">' +
'<input type="button" onclick="removeThis(' + i + ');" class="btn btn-danger btn-sm" name="minus" id="minus' + i + '" value="-" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;"></div>' +
'<div> <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(' + (i++) + ');"></div>');
}
function removeThis(j) {
$("#introlabelname" + j).remove();
$("#minus" + j).remove();
}
</script>
Here my problem is the id is increasing like introlabelname0,introlabelname1,introlabelname2.. this but while suppose deleting introlabelname1 textbox and adding again its coming introlabelname0,introlabelname2,introlabelname3 like this. Here i need suppose introlabelname1 deleting from introlabelname0,introlabelname1,introlabelname2.. it should introlabelname0,introlabelname1 and if adding again it should introlabelname0,introlabelname1,introlabelname2. Always all textbox id will remain serially from 0,1,2... and so on. Here is my full code. Please help me.
You can also do like this.
1.I added var i = $(".inputBox").length + 1; this line in addMore function it calculate the current input box count and add serialize number to new input box.
2.Also I include serialize() function it makes serialize your input box and button ids.
function addMore(i) {
var i = $(".inputBox").length + 1;
$("#plus").remove();
$('#intro-box').append('<div><input type="text" style="width:85%;float:left; margin-bottom:5px;" class="form-control inputBox" id="introlabelname' + i + '" name="introlabelname" placeholder="Label Name" value="">' +
'<input type="button" onclick="removeThis(' + i + ');" class="btn btn-danger btn-sm" name="minus" id="minus' + i + '" value="-" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;"></div>' +
'<div> <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(' + (i++) + ');"></div>');
}
function removeThis(j) {
$("#introlabelname" + j).remove();
$("#minus" + j).remove();
serialize();
}
function serialize(){
var i=1;
$(".inputBox").each(function(){
$(this).attr("id", "introlabelname"+i);
$(this).next().attr("id", "minus"+i);
i++;
});
}
I think you just need to decrement the a variable when you remove a row:
function removeThis(j) {
$("#introlabelname" + j).remove();
$("#minus" + j).remove();
a = a - 1;
}
The easy way is to loop over all the input box, and create the new ID(s) with index value. First of all give the text box class name :
class="form-control inputBox"
Then add this function :
function repopulate() {
$( '.inputBox' ).each( function ( i, e) {
$( this ).attr( 'id','introlabelname' + i );
$( this ).next().attr( 'onClick', function (old,n) {
return 'removeThis(' + i + ')';
});
$( this ).next().attr( 'id', function (old,n) {
return 'minus' + i;
});
})
}
Last, for each function calling, call this function :
repopulate();
Here is updated DEMO
p/s : you should edit the HTML,it not properly structured

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