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);
Related
I have a design related question.
I have a bill to add product. One product is added per line.
One Product added per line image
When I add a product, I also display its warranty in the Warranty column:
Selected product shows warranty in Warranty Column
But when I add any other product, I cannot display its Warranty.
Cannot Display Warranty in subsequent products
My HTML where dropdown options are coming dynamically:
<tbody style="border: 1px solid rgba(0,0,0,0.35); height: 34px; line-height: 34px;">
<tr class="text-center">
<td>
<select id="myDropdown" name="bill_product[]" onChange="dropdownTip(this.value)">
<option disabled selected value="">Select Product</option>
<option id="1" value="31/01/2020">Product #1</option>
<option id="2" value="31/01/2030">Product #2</option>
<option id="3" value="31/01/2040">Product #3</option>
</select>
</td>
<td>
<input name="txtbox" type="text" id="txtbox" />
</td>
<td>
<button type="button" class="btn btn-danger btn-xs disabled">
<i class="fa fa-times"></i>
</button>
</td>
</tr>
</tbody>
My JS for adding row to bill:
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr class='text-center'>");
var cols = "";
cols += '<td><select name="bill_product[]"><option disabled selected value="">Select Product</option><cms:pages masterpage="product.php"><option value="<cms:show k_page_id />"><cms:show k_page_title /></option></cms:pages></select></td>';
cols += '<td><input type="text" id="txtbox" name="txtbox" /></td>';
cols += '<td><button type="button" class="ibtnDel btn btn-danger btn-xs"><i class="fa fa-times"></i></button></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
My Code to display the warranty end date:
$(document).ready(function() {
$("#myDropdown").change(function() {
var selectedValue = $(this).val();
$("#txtbox").val(selectedValue);
});
});
ISSUE: I am unable to display the value of the warranty date on any product after the first one.
Please help.
P.S.: I am using CouchCMS to dynamically bring my values to the option tag of select.
Here's the solution I propose, I get rid off not-native JS by the way, it allows it to fit with any solution :
<tbody style="border: 1px solid rgba(0,0,0,0.35); height: 34px; line-height: 34px;">
<tr class="text-center">
<td>
<select id="myDropdown" name="bill_product[]" onChange="dropdownTip(this.value)">
<option disabled selected value="">Select Product</option>
<option id="1" value="31/01/2020">Product #1</option>
<option id="2" value="31/01/2030">Product #2</option>
<option id="3" value="31/01/2040">Product #3</option>
</select>
</td>
<td>
<input name="txtbox" type="text" id="txtbox" />
</td>
<td>
<button type="button" class="btn btn-danger btn-xs disabled">
Delete
</button>
</td>
</tr>
</tbody>
// Line removal
let delBtns = document.querySelectorAll(".del-btn");
[].forEach.call(delBtns, function(delBtn){
delBtn.addEventListener('click', function(event){
let line = event.target.dataset.line;
let lineToRemove = document.querySelector("#line-"+line);
lineToRemove.remove();
})
});
// Input update
let productDropDowns = document.querySelectorAll("select");
[].forEach.call(productDropDowns, function(dropDown){
dropDown.addEventListener('change', function(event){
let line = event.target.dataset.line;
document.querySelector('#line-'+line+' input').value = event.target.value;
})
});
// New line button
let count = 0;
let newLineButton = document.querySelector("#newLineTrigger");
newLineButton.addEventListener('click', function(){
count++;
let tableBody = document.querySelector('tbody');
let newLine = document.createElement('tr');
newLine.id = 'line-' + count;
tableBody.appendChild(newLine);
newLine = document.querySelector('#line-' + count);
let col1 = document.createElement('td');
let select = document.createElement('select');
select.id = 'drop' + count;
select.dataset.line = count;
select.addEventListener('change', function(event){
let line = event.target.dataset.line;
document.querySelector('#line-'+line+' input').value = event.target.value;
})
for(let i=0; i<3; i++){
let option = document.createElement('option');
option.value = i;
option.innerText = 'option ' + i;
select.appendChild(option);
}
col1.appendChild(select);
let col2 = document.createElement('td');
let textBox = document.createElement('input');
textBox.id = 'textBox'+count;
textBox.name = 'textBox'+count;
col2.appendChild(textBox);
let col3 = document.createElement('td');
let newDelBtn = document.createElement('button');
newDelBtn.className = "del-btn";
newDelBtn.dataset.line = count;
newDelBtn.innerText = "Delete";
newDelBtn.addEventListener('click', function(event){
let line = event.target.dataset.line;
let lineToRemove = newLine;
lineToRemove.remove();
});
col3.appendChild(newDelBtn);
newLine.appendChild(col1);
newLine.appendChild(col2);
newLine.appendChild(col3);
tableBody.appendChild(newLine);
});
I don't see the triggerring element '#addrow' which adds the row. Could you update the fiddle to include this button, please?
The ids for all warranty input field is same, which is "txtbox". You can use the counter variable to have separate ids for all warranty fields.
This is one of the rows in my table.
<td>
<select id="itemcodeid" name="itemcode[]" class="form-control itemcode">
<option></option>
#foreach($productsdata as $d)
<option>{{$d->itemcode}}</option>
#endforeach
</select>
</td>
I am using Select2 to fill data.
<script type="text/javascript">
$("#itemcodeid").select2
({
placeholder: "Select Itemcode",
allowClear: true
});
</script>
But when i add rows to table how to refer the upcoming rows with id. Because this works only on first row.
Below is image of first row.
But in Other rows i am unable to type and select(second image) because id reference is not done so kindly tell how to refer id of the rows added.
Help or suggestion will be highly useful.Thank You.
This is the code which gets executed when i press the plus button(verify image).
<script type="text/javascript">
$('.addrow').on('click',function()
{ addrowfn();
});
function addrowfn()
{
var tr = '<tr>'+
'<td>'+
'<select id="itemcodeid" name="itemcode[]" class="form-control itemcode">'+
'<option></option>'+
'#foreach($productsdata as $d)'+
'<option>{{$d->itemcode}}</option>'+
'#endforeach'+
'</select>'+
'</td>'+
'<td><input type="text" name="proname[]" class="form-control proname"></td>'+
'<td><input type="text" name="actualprice[]" class="form-control actualprice"></td>'+
'<td><input type="text" name="discount[]" class="form-control discount"></td>'+
'<td><input type="text" name="gst[]" class="form-control gst"></td>'+
'<td><input type="text" name="quantity[]" class="form-control quantity"></td>'+
'<td><input type="text" name="finalprorate[]" class="form-control finalprorate"></td>'+
'<td><input type="text" name="finalbillrate[]" class="form-control finalbillrate"></td>'+
'<td>'+
'<a href="#" class="remove btn btn-danger">'+
'<center>'+
'<i class="glyphicon glyphicon-remove"></i>'+
'</center>'+
'</a>'+
'</td>'+
'</tr>';
$('tbody').append(tr);
}
$('body').on('click','.remove',function()
{ var l=$('tbody tr').length;
console.log(l);
if(l==1)
{ alert('You Cannot Remove all Rows!!!');
}
else
$(this).parent().parent().remove();
});
</script>
Kindly Tell me if there are any corrections.
I'm not sure if this code works, as I haven't tested it, but I would, at minimum, make these two changes:
Listen for the appended node using a MutationObserver, then turn
the regular select into a select2();
Create a variable to keep track of the rows, and make each select's ID dynamic, e.g. 'itemcodeid_3' and 'itemcodeid_5' etc. Do the same for 'name' attribute
var target = document.getElementById('<INSERT_ID_HERE>');
var rows = 1;
if (target) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation && mutation.addedNodes) {
mutation.addedNodes.forEach(function(el) {
if (el && el.nodeName === "SELECT") {
$(el).select2();
}
});
}
});
});
observer.observe(target, {
childList: true
});
} // end if
$('.addrow').on('click',function()
{
addrowfn();
});
function addrowfn()
{
rows++;
var tr = '<tr>'+
'<td>'+
'<select id="itemcodeid_" ' + rows + ' name="itemcode_' + rows + '[]" class="form-control itemcode">'+
'<option></option>'+
'#foreach($productsdata as $d)'+
'<option>{{$d->itemcode}}</option>'+
'#endforeach'+
'</select>'+
'</td>'+
'<td><input type="text" name="proname[]" class="form-control proname"></td>'+
'<td><input type="text" name="actualprice[]" class="form-control actualprice"></td>'+
'<td><input type="text" name="discount[]" class="form-control discount"></td>'+
'<td><input type="text" name="gst[]" class="form-control gst"></td>'+
'<td><input type="text" name="quantity[]" class="form-control quantity"></td>'+
'<td><input type="text" name="finalprorate[]" class="form-control finalprorate"></td>'+
'<td><input type="text" name="finalbillrate[]" class="form-control finalbillrate"></td>'+
'<td>'+
'<a href="#" class="remove btn btn-danger">'+
'<center>'+
'<i class="glyphicon glyphicon-remove"></i>'+
'</center>'+
'</a>'+
'</td>'+
'</tr>';
$('tbody').append(tr);
}
$('body').on('click','.remove',function()
{
var l=$('tbody tr').length;
console.log(l);
if(l==1)
{
alert('You Cannot Remove all Rows!!!');
}
else {
$(this).parent().parent().remove();
}
});
It may not work because it sees the appended node as instead of ...have to test
Additionally, you may wish to look at using a template engine for this, such as John Resig's jQuery solution or Mustache.js,
Handlebars.js
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.
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.
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"> <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.