Codepen https://codepen.io/mehmetmasa-the-selector/pen/RwBQbOr
When I click the button, I add a new field. One of the added fields (radio button) needs to be selected. But since the user can add/delete, I can't give the value value.
HTML Code
<div id="answer">
<div class="form-group d-flex">
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input trueAnswer" type="radio" name="trueAnswer">Doğru Cevap </label>
</div>
<input class="form-control answer" type="text" placeholder="Cevabı Yazınız">
<button class="btn btn-primary ml-3 col-md-1" type="button" id="addAnswer">Yeni Cevap</button>
</div>
</div>
JS Code
$('#addAnswer').on('click', function() {
$('<div class="form-group d-flex">' +
'<div class="form-check">' +
'<label class="form-check-label">' +
'<input class="form-check-input trueAnswer" type="radio" name="trueAnswer">Doğru Cevap' +
'</label>' +
'</div>' +
'<input class="form-control answer" type="text" placeholder="Cevabı Yazınız">' +
'<button class="btn btn-danger ml-3 col-md-1 deleteAnswer" type="button" >Cevabı Sil</button>' +
'</div>').appendTo('#answer');
});
$('#addQuestion').on('click', function() {
let answer = [];
$('#answer .form-group').map(function(i, val) {
if ($(val).find('.answer').val().length > 0)
answer.push({
name: $(val).find('.answer').val(),
trueAnswer: $(val).find('.trueAnswer').val()
});
});
let categoryID = $('#category').val();
let question = $('#question').val();
let questionNo = $('#questionNo').val();
let colorpicker = $('#colorpicker').val();
let formData = new FormData();
formData.append("categoryID", categoryID);
formData.append("question", question);
formData.append("questionNo", questionNo);
formData.append("colorpicker", colorpicker);
for (var i = 0; i < answer.length; i++) {
formData.append('answer' + [i], answer[i].name);
formData.append('answer' + [i], answer[i].trueAnswer);
}
How can I find which answer the user chose?
Related
I am trying to succeed with populating dynamically generated form fields from a database via xmlhttp. First row is "static" and when I type in the SKU-field the name[] field gets the data correct from the database. When I click the "#addrow" button a new row is added and here I want to be able to type in the SKU-field and have the name[] field get data from the database. Right now what happens is that the row above gets updated when I type in the SKU-field.
I have added data-attributes for the SKU-field and name-field and also a counter so I somehow could select the field data-names and from this be able to parse the value to the right name-field in the right row?
I have tried to add a variable and see if I can get this to parse the database value to the right name-field, but it does not work:
var field = "name" + $(this).attr("data-dynid");
field.value = myObj[0];
I just need to figure out how to have the code recognize which SKU-field I am typing in (with the data-attribute counter) and from the counter select the name-field with the same counter value.
*** UPDATE ****
So I found a way to locate a form field from data-attribute and assign a value to it. Now I need to figure out how to have the code recognize the SKU field I am typing in, in order to retreive the SKU data-attribute number and use this dynamically to locate the form field to parse the data to.
var elements = document.querySelectorAll('[data-dynname="name-1"]');
elements[0].value = myObj[0];
HTML
<form method="post" action="">
<div class="row">
<div class="col-lg-12">
<div id="inputFormRow">
<div class="row">
<div class="form-group col-md-2">
<label class="form-control-label" for="sku">Varenummer</label>
<input type="text" class="form-control searchInput" name="sku[]" placeholder="Varenummer" autocomplete="off" onkeyup="GetDetail(this.value)" value="">
</div>
<div class="form-group col-md-4">
<label class="form-control-label" for="name">Navn</label>
<input type="text" class="form-control name" name="name[]" placeholder="Navn" autocomplete="off">
</div>
<div class="form-group col-md-2">
<label class="form-control-label" for="content">Tekst</label>
<input type="text" class="form-control" name="text[]" placeholder="Tekst" autocomplete="off">
</div>
<div class="form-group col-md-1">
<label class="form-control-label" for="normalprice">Normalpris</label>
<input type="text" class="form-control" name="beforeprice[]" placeholder="Normalpris" autocomplete="off">
</div>
<div class="form-group col-md-1">
<label class="form-control-label" for="offerprice">Tilbudspris</label>
<input type="text" class="form-control" name="offerprice[]" placeholder="Tilbudspris" autocomplete="off">
</div>
<div class="form-group col-md-1">
<label class="form-control-label" for="size">Størrelse</label>
<select class="form-control" name="size[]" placeholder="Størrelse" autocomplete="off">
<option value="A4" selected="">A4</option>
<option value="A5">A5</option>
<option value="A10">A10</option>
</select>
</div>
<div class="form-group col-md-1">
<label class="form-control-label" for="removeRow"> </label>
<button id="removeRow" type="button" class="form-control btn btn-danger">Fjern</button>
</div>
</div>
</div>
<div id="newRow"></div>
<button id="addRow" type="button" class="btn btn-info">Add Row</button>
</div>
</div>
</form>
Javascript
<script type="text/javascript">
// add row
var counter = 1;
$("#addRow").click(function () {
var html = '';
html += '<div id="inputFormRow">';
html += '<div class="row">';
html += '<div class="form-group col-md-2">';
html += '<input type="text" class="form-control searchInput" data-dynid ="' + counter + '" name="sku[]" placeholder="Varenummer" autocomplete="off" onkeyup="GetDetail(this.value)">';
html += '</div>';
html += '<div class="form-group col-md-4">';
html += '<input type="text" class="form-control name" data-dynname ="name-' + counter + '" name="name[]" placeholder="Navn" autocomplete="off">';
html += '</div>';
html += '<div class="form-group col-md-2">';
html += '<input type="text" class="form-control" name="text[]" placeholder="Tekst" autocomplete="off">';
html += '</div>';
html += '<div class="form-group col-md-1">';
html += '<input type="text" class="form-control" name="beforeprice[]" placeholder="Normalpris" autocomplete="off">';
html += '</div>';
html += '<div class="form-group col-md-1">';
html += '<input type="text" class="form-control" name="offerprice[]" placeholder="Tilbudspris" autocomplete="off">';
html += '</div>';
html += '<div class="form-group col-md-1">';
html += '<input type="text" class="form-control" name="size[]" placeholder="Størrelse" autocomplete="off">';
html += '</div>';
html += '<div class="form-group col-md-1">';
html += '<button type="button" class="form-control btn btn-danger removeRow">Fjern</button>';
html += '</div>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
counter++;
console.log(counter);
});
// remove row
$(document).on('click', '.removeRow', function () {
$(this).closest('#inputFormRow').remove();
});
</script>
<script>
// onkeyup event will occur when the user
// release the key and calls the function
// assigned to this event
function GetDetail(str) {
if (str.length == 0) {
document.getElementsByName("first_name")[0].value = "";
return;
}
else {
// Creates a new XMLHttpRequest object
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
// Defines a function to be called when
// the readyState property changes
if (this.readyState == 4 &&
this.status == 200) {
// Typical action to be performed
// when the document is ready
var myObj = JSON.parse(this.responseText);
// Returns the response data as a
// string and store this array in
// a variable assign the value
// received to first name input field
//var el = document.getElementsByName('name[]')[0];
//var el = document.getElementsByClassName("name");
//var r2 = console.log(el).closest("name[]");
document.getElementsByName("name[]")[0].value = myObj[0];
//r2.value = myObj[0];
}
};
// xhttp.open("GET", "filename", true);
xmlhttp.open("GET", "pages/actions/load-products.php?user_id=" + str, true);
// Sends the request to the server
xmlhttp.send();
}
}
</script>
I have made contact list app which displays contact details. By Default it shows 2 contact details.
In index.html I have made 2 functions called showContacts() and editContact(id).
I am dynamically populating div tags i.e editcontact & contactlist in index.html
When I click on edit button it should show 3 input elements to take input from user and one submit button I tried to implement it (see code below) but only search bar disappear's and only default contacts are shown which should not be shown and it should display editing form.
var array = [];
function Person(fullName, number, group) {
this.fullName = fullName;
this.number = number;
this.group = group;
array.push(this);
}
Person.prototype.getFullName = function() {
return this.fullName + ' ' + this.number + ' ' + this.group;
}
var p1 = new Person("Jonathan Buell", 5804337551, "family");
var p2 = new Person("Patrick Daniel", 8186934432, "work");
console.log(array);
document.getElementById("contactlist").innerHTML = '';
function showContacts() {
for (var i in array) {
var id = i;
contactlist.innerHTML +=
`
<ul>
<div>
<p>Name: ` + p1.fullName + `</p>
<p>Number: ` + p1.number + `</p>
<p>Group: ` + p1.group + `</p>
<button type="button" class="btn btn-warning" onclick="editContact(` + id + `)">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
`
}
}
showContacts();
function editContact(id) {
document.getElementById("search").style.display = 'none';
document.getElementById("contactList").style.display = 'none';
document.getElementById("editcontact").style.display = '';
document.getElementById("editcontact").innerHTML =
`<div>
<input type="text" placeholder="Name here" id="nameInput2" value="` + array[id].fullName + `">
<input type="tel" placeholder="Number here" id="numberInput2" value="` + array[id].number + `">
<input type="text" placeholder="Group Here" id="groupInput2" value="` + array[id].group + `">
<button type="button" class="btn btn-success">Submit</button>
</div>`;
}
<div class="header">
<div id="dropdown">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Sort by Group
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>All</li>
<li>Work</li>
<li>Family</li>
</ul>
</div>
</div>
<div class="title">
<h2>All Contacts</h2>
</div>
<div class="button" id="addButton">
<p>
<a href="#">
<span class="glyphicon glyphicon-plus-sign"></span>
</a>
</p>
</div>
</div>
<div id="search">
<form>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
</div>
<div id="contactlist">
</div>
<div id="editcontact">
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="index.css">
screenshots :
1) Before on click editContact :
2) After onclick editContact :
Live demo can be seen here :
https://jsfiddle.net/w2hoqmts/
A couple of things.
You made a typo with your contactlist in your html (should be contactList).
In your loop for showContacts you are setting id as index and should be like
function showContacts() {
for (var i in array) {
var id = array[i].number;
document.getElementById("contactList").innerHTML +=
'<ul><div><p>Name: ' + array[i].fullName + '</p><p>Number: ' + array[i].number + '</p><p>Group: ' + array[i].group + '</p>' +
'<button type="button" class="btn btn-warning" onclick="editContact(' + id + ')">Edit</button>' +
'<button type="button" class="btn btn-danger">Delete</button>' +
'</div>';
}
}
Your editContact method is using the id as an index (as previous), which is wrong. You could do something like this instead (see code below). I filter the array with people based on the unique id provided from the link when you click edit.
function editContact(id) {
var obj = array.filter(function (ele) {
console.dir(ele);
if (ele.number === id) return ele;
});
console.dir(obj);
document.getElementById("search").style.display = 'none';
document.getElementById("contactList").style.display = 'none';
document.getElementById("editcontact").style.display = '';
document.getElementById("editcontact").innerHTML =
'<div>'+
'<input type="text" placeholder="Name here" id="nameInput2" value="'+ obj[0].fullName + '">'+
'<input type="tel" placeholder="Number here" id="numberInput2" value="' + obj[0].number + '">' +
'<input type="text" placeholder="Group Here" id="groupInput2" value="' + obj[0].group + '">' +
'<button type="button" class="btn btn-success">Submit</button>'+
'</div>';
}
I've made a updated fiddle based on your own
https://jsfiddle.net/w2hoqmts/3/
Following changes should be made in editContact() and showContacts() function.
function showContacts(){
for(var i in array){
var id = i;
contactlist.innerHTML +=
`
<ul>
<div>
<p>Name: `+ p1.fullName +`</p>
<p>Number: `+ p1.number +`</p>
<p>Group: `+ p1.group +`</p>
<button type="button" class="btn btn-warning" onclick="editContact(`+ id +`)">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
`
}
}
showContacts();
function editContact(id) {
document.getElementById("search").style.display = 'none';
document.getElementById("contactlist").style.display = 'none';
document.getElementById("editcontact").style.display = '';
document.getElementById("editcontact").innerHTML =
`<div>
<input type="text" placeholder="Name here" id="nameInput2" value="`+array[id].fullName+`">
<input type="tel" placeholder="Number here" id="numberInput2" value="`+array[id].number+`">
<input type="text" placeholder="Group Here" id="groupInput2" value="`+array[id].group+`">
<button type="button" class="btn btn-success">Submit</button>
</div>`;
}
I am trying to add multiple fields by clicking one plus button. Then I have four arrays for four specific text fields: company, from, to, and year. If I click the button, I will get the four fields. I want to enter values and have the values saved in the four arrays. When I click the button again the same thing should happen.
The array saves only the first value from each field and the other value is null. How can I save all of the values in the arrays?
var company = [];
var from = [];
var to = [];
var year = [];
var scntDiv = $('#addmorefieldexp');
var i = $('#addmorefieldexp p').size() + 1;
/* $('#pexp').live('click', function() */
$("#pexp").click(function(){
$( ' <br><br>'
+'<label for="inputPassword3" class="col-sm-2 control-label">Company Name</label>'
+'<div class="col-sm-2">'
+'<input type="text" class="form-control" name="field_company[]" value="" id="company">'
+'</div>'
+'<label for="inputPassword3" class="col-sm-1 control-label">From</label>'
+'<div class="col-sm-2">'
+'<input type="text" class="form-control" name="field_from[]" value="" id="from">'
+'</div>'
+'<label for="inputPassword3" class="col-sm-1 control-label">To</label>'
+'<div class="col-sm-2">'
+'<input type="text" class="form-control" name="field_to[]"value="" id="to">'
+'</div>'
+'<label for="inputPassword3" class="col-sm-1 control-label">Year</label>'
+'<div class="col-sm-1">'
+'<input type="text" class="form-control" name="field_year[]"value="" id="year">'
+'</div>').appendTo(scntDiv);
var add_company = $("input[name$='field_company[]']").val();
company.push(add_company);
var add_from = $("input[name$='field_from[]']").val();
from.push(add_from);
var add_to = $("input[name$='field_to[]']").val();
to.push(add_to);
var add_year = $("input[name$='field_year[]']").val();
year.push(add_year);
console.log(company, from, to, year);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="form-group" id="experience">
<label class="col-sm-2 control-label">Employment Experience</label>
<div class="col-sm-4" id="checkbox" value="">
<input type="radio" name="exp" class="expp" value="Yes">Yes
<input type="radio" name="exp" class="expp" value="No">No
<button class="btn btn-lg btn-sm btn-primary btn-circle" id="pexp"><i class="fa fa-plus"></i>
</button>
</div>
</div>
<div class="form-group text-center" id="addmorefieldexp">
<p>
</p>
</div>
You just need to write a for loop to iterate through all of the input fields, like so:
var companyField = $("input[name$='field_company']");
for (var i;i<companyField.length;i++) {
var companyValue = companyField[i].val();
company.push(companyValue);
}
var fromField = $("input[name$='field_from']");
for (var i;i<fromField.length;i++) {
var fieldValue = fromField[i].val();
from.push(fieldValue);
}
var toField = $("input[name$='field_to']");
for (var i;i<toField.length;i++) {
var toValue = toField[i].val();
to.push(toValue);
}
var yearField = $("input[name$='field_year']");
for (var i;i<yearField.length;i++) {
var yearValue = yearField[i].val();
year.push(yearValue);
}
I is done!!! I have to add this to save value on the array.
var inps = document.getElementsByName('field_company[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
company.push(inp.value);
Good day, i have this section of javascript that's causing me trouble
https://jsfiddle.net/o5x8qgvt/2/
When i add a new field the position gets incremented when i delete a field the position is repopulated but on product name it doesn't repopulate the fields it gives me blank even if i added data in each of them. Can you please help me out?
Javascript:
// setup an "add a tag" link
var $addTagLink = $('<button href="#" class="btn btn-info add_tag_link">Adauga Produs</button>');
$('.form-buttons > .btn-group').prepend($addTagLink);
var $newLinkLi = $('.append-me');
jQuery(document).ready(function() {
// Get the ul that holds the collection of product-group
var $collectionHolder = $('#products-group');
// add the "add a tag" anchor and li to the product-group ul
$collectionHolder.append($newLinkLi);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addTagLink.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// add a new tag form (see code block below)
addTagForm($collectionHolder, $newLinkLi);
typeInitialize();
});
});
function regenerateTagList() {
var vals = $('.product-group > .product-counter > input').toArray().map(function(v, i) {return v.value;});
var products = $('.product-group > .product-name > span > input:last').toArray().map(function(v, i) {return v.value;});
console.log(products);
$('.product-group').remove();
$('#products-group').data('index', 1);
for (var i = 0; i < vals.length; i++) {
if (vals[i] !== i + 1) {
vals[i] = i + 1;
}
addTagForm($('#products-group'), $newLinkLi);
typeInitialize();
$('.product-group > .product-counter > input:last').val(vals[i]);
$('.product-group > .product-name > span > input:last').val(products[i]);
}
}
function addTagForm($collectionHolder, $newLinkLi) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
if (index === 0) {
index = 1;
}
// Replace '$$name$$' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm = prototype.replace(/__name__/g, index);
// increase the index with one for the next item
$collectionHolder.data('index', index + 1);
// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi = $('<tr class="product-group"></tr>').append(newForm);
// also add a remove button, just for this example
//$('<button type="button" class="product-highlight btn btn-primary">Highlight</button>
// <button type="button" class="remove-tag btn btn-primary">Sterge</button>').appendTo($newFormLi);
$newLinkLi.append($newFormLi);
// handle the removal, just for this example
$('.remove-tag').click(function(e) {
e.preventDefault();
$(this).closest('tr').remove();
regenerateTagList();
return false;
});
$('.product-highlight').on('click', function(e) {
e.preventDefault();
$(this).closest('tr').toggleClass('toggle-highlight');;
});
}
// Initialize Typeahead
function typeInitialize() {
// Create typeahead instance
var url = Routing.generate('offer_ajax_search', {
name: 'WILDCARD'
});
// Trigger typeahead + bloodhound
var products = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) {
console.log('fired');
return obj.u_name;
},
prefetch: '/export/json/products.json',
remote: {
url: url,
wildcard: 'WILDCARD',
}
});
products.initialize();
$('.product-group').find('.typeahead:last').typeahead({
minLength: 3,
highlight: true,
limit: 10,
}, {
name: 'product',
display: 'u_name',
source: products.ttAdapter()
}).on('typeahead:select', function(e, datum) {
e.preventDefault();
/* Act on the event */
var information = '<div class="col-md-2"><label for="boxCode" class="label-control">BEX Code</label><input class="form-control" type="text" disabled="true" value="' + datum.u_bexCode + '"/></div>';
information += '<div class="col-md-2"><label for="base-price">Pret de baza</label><input class="form-control " type="text" disabled="true" value="' + datum.u_image + '"/></div>';
var div = $(this).parent().closest('.form-group').find('.product-information');
$(div).empty().append(information);
}).on('typeahead:autocomplete', function(e, datum) {
e.preventDefault();
/* Act on the event */
var information = '<div class="col-md-2"><label for="boxCode" class="label-control">BEX Code</label><input class="form-control" type="text" disabled="true" value="' + datum.u_bexCode + '"/></div>';
information += '<div class="col-md-2"><label for="base-price">Pret de baza</label><input class="form-control " type="text" disabled="true" value="' + datum.u_image + '"/></div>';
var div = $(this).parent().closest('.form-group').find('.product-information');
$(div).empty().append(information);
});
$("input[type='text']").on("click", function() {
$(this).select();
});
}
HTML:
<div class="row">
<div class="col-md-12">
<form name="offer" method="post" action="/app_dev.php/offer-generator/new/submited" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label required" for="offer_name">Name</label><div class="col-sm-10"><input type="text" id="offer_name" name="offer[name]" required="required" maxlength="255" class="form-control"></div>
</div>
<div id="products-group" data-prototype="<td class="product-counter col-md-1"><input type="text" id="offer_products___name___position" name="offer[products][__name__][position]" disabled="disabled" required="required" class="counter form-control" value="__name__" /></td>
<td class="product-name"><input type="text" id="offer_products___name___name" name="offer[products][__name__][name]" required="required" class="typeahead product form-control" name="product" id="products" data-provider="product" placeholder="Nume Produs" autocomplete="false" /></td>
<td class="col-md-1"><input type="text" id="offer_products___name___price" name="offer[products][__name__][price]" required="required" class="form-control" /></td>
<td class="col-md-1"><input type="text" id="offer_products___name___quantity" name="offer[products][__name__][quantity]" required="required" class="form-control" /></td>
<td class="product-action">
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="product-highlight btn btn-warning">Highlight</button>
<button type="button" class="remove-tag btn btn-danger">delete</button>
</div>
</td>
"><table class="table table-striped table-hover table-bordered append-me">
<thead>
<tr>
<th class="col-md-1">Position</th>
<th>Product</th>
<th class="col-md-1">Price</th>
<th class="col-md-1">Quantity</th>
<th class="col-md-2">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table></div>
</form></div>
<div class="form-buttons">
<div class="btn-group" role="group" aria-label="..."><button href="#" class="btn btn-info add_tag_link">Add Product</button>
<button type="submit" id="offer_save" name="offer[save]" class="btn-default btn">Create Offer</button>
<button type="submit" id="offer_send_email" name="offer[send_email]" class="btn-default btn">Send Email</button>
<button type="submit" id="offer_export_excel" name="offer[export_excel]" class="btn-default btn">Export Excel</button>
<button type="submit" id="offer_export_pdf" name="offer[export_pdf]" class="btn-default btn">Export PDF</button>
</div>
</div>
<div class="form-group"><div class="col-sm-2"></div><div class="col-sm-10"><div id="offer_products" data-prototype="<div class="form-group"><label class="col-sm-2 control-label required">__name__label__</label><div class="col-sm-10"><div id="offer_products___name__"><div class="form-group"><label class="col-sm-2 control-label required" for="offer_products___name___pricePerLine">Line Total</label><div class="col-sm-10"><input type="text" id="offer_products___name___pricePerLine" name="offer[products][__name__][pricePerLine]" required="required" class="form-control" /></div>
</div></div></div>
</div>"></div></div>
</div><input type="hidden" id="offer__token" name="offer[_token]" class="form-control" value="cSVdt50kupA_BwFeY4T43PslnfjiA-UgjT4EA_HBdqs">
</div>
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.