Storing array of values in one variable - javascript

This is My Code. I'm preparing a offline quiz system. This code shows multiple questions with there option field. Now in radio variable, currently it stores the option of question submitted by user who's name is q1. Since the name of every question set is dynamic,how can I store multiple values in radio variable ?
Like option of q1, q2... and so on ...
<script type="text/javascript">
var currentPath = ((location+"").replace(/%20/g, " ").replace("file:///", "").replace("/", "\\").replace("index.html", ""));
var pad = currentPath+"\\quiz.mdb";
//var strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pad;
var strConn = "Provider=microsoft.ace.oledb.12.0;Data Source=" + pad;
var cn = new ActiveXObject("ADODB.Connection");
cn.Open(strConn);
var rs = new ActiveXObject("ADODB.Recordset");
var SQL = "SELECT * FROM ques_bank WHERE quizno = 'q_001'";
rs.Open(SQL, cn);
var sList = "<form target='sendinfo' id='infoform' onSubmit='return handleClick()'>";
while (!rs.EOF) {
sList = sList +
"<p>"+rs("question")+ "</p><br>"+
"<input type='radio' name='q"+ rs("ID") +"' value='a' />"+rs("optionA")+"<br>"+
"<input type='radio' name='q"+ rs("ID") +"' value='b' />"+rs("optionB")+"<br>"+
"<input type='radio' name='q"+ rs("ID") +"' value='c' />"+rs("optionC")+"<br>"+
"<input type='radio' name='q"+ rs("ID") +"' value='d' />"+rs("optionD")+"<br>"+
"<input type='radio' name='q"+ rs("ID") +"' value='e' />"+rs("optionE")+"<br>"+
"<input type='text' id='rank_list' name='q_id' value='"+ rs("ID") +"' /><br>"+
"<hr>";
rs.MoveNext();
}
document.write(sList+"<input type='submit' value='Submit'/></form>");
function test() {
}
//submit function
function handleClick() {
var radios = document.getElementsByName("q1");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1) {
alert("Please Select Radio");
}
//event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
rs.Close();
cn.Close();
</script>

Related

Radio button inside div

I have a form html which can add the form dynamically. I have problem with radio button, it can only select one option (even when the radio button is in different tag). I search the solution, one solution is to change the name of the radio button. Is there any other way to do it? Because my other input all use same name and when submit the form all input can be collected in an array.
If there's no other way, how can I change the name of the radio button for the cloned element?
Here's my code:
app.get('/form', function (req, res) {
var html='';
html += `<head>
<style>
.formset {
border-style: solid;
border-width: 1px;
}
</style>
<script>
var id=1
function myFunction() {
id++
var elmnt = document.getElementById("div1")
var cln = elmnt.cloneNode(true)
cln.id = "div"+id
document.getElementById("divParent").appendChild(cln);
}
</script>
</head>`;
html +="<body>";
html += "<p>Click the button to make a BUTTON element with text.</p>";
html += '<button onclick="myFunction()">Add form</button>';
html += "<form action='/thank' method='post' name='form1'>";
html += "<div id='divParent'>";
html += "<div id='div1' name='formset' class='formset'>";
html += "<p>Name: <input type= 'text' name='name'></p>";
html += "<p>Sex: Male <input type='radio' name='gender' value='male'>"
html += " Female <input type='radio' name='gender' value='female'></p>"
html += "<p>Email: <input type='text' name='email'></p>";
html += "<p>Address:<input type='text' name='address'></p>";
html += "<p>Mobile number:<input type='text' name='mobilno'></p>";
html += "</div>";
html += "</div>";
html += "<input id='input1' type='submit' value='submit'>";
html += "<INPUT type='reset' value='reset'>";
html += "</form>";
html += "</body>";
res.send(html);
});
And the code to handle the form:
app.post('/thank', urlencodedParser, function (req, res){
var reply='';
reply += "<br>Array length is : " + req.body.name.length;
reply += "<br>Your name is : " + req.body.name;
reply += "<br>Sex is : " + req.body.gender;
reply += "<br>Your E-mail id is : " + req.body.email;
reply += "<br>Your address is : " + req.body.address;
reply += "<br>Your mobile number is : " + req.body.mobilno;
res.send(reply);
});
I think you need change name of the radio input, add class to radio to make it can be found by getElementsByClassName.
html += "<p>Sex: Male <input type='radio' class='gender' name='gender' value='male'>"
html += " Female <input type='radio' class='gender' name='gender' value='female'></p>"
//change the name, add id to the end
function changeName(element, id) {
var x = element.getElementsByClassName("gender");
var i;
for (i = 0; i < x.length; i++) {
x[i].name += id;
}
}
function myFunction() {
id++
var elmnt = document.getElementById("div1")
var cln = elmnt.cloneNode(true)
cln.id = "div"+id
//change radio id
changeName(cln, id);
document.getElementById("divParent").appendChild(cln);
}

How to check if fields are empty on all rows?

What will I do with my jquery dialog? Pop up notification that fields are empty have just appeared on the first row empty fields. But on succeeding rows, this is not functioning though fields are empty.
function Save() {
var par = $(this).parent().parent();
var tdFirstName = par.children("td:nth-child(2)");
var tdLastName = par.children("td:nth-child(3)");
var tdAge = par.children("td:nth-child(4)");
var tdButtons = par.children("td:nth-child(5)");
tdFirstName.html(tdFirstName.children("input[type=text]").val());
tdLastName.html(tdLastName.children("input[type=text]").val());
tdAge.html(tdAge.children("input[type=text]").val());
tdFirstName.html("<input type='text' id='txtName' value='" + tdFirstName.html() + "'/>");
tdLastName.html("<input type='text' id='txtPhone' value='" + tdLastName.html() + "'/>");
tdAge.html("<input type='text' id='txtEmail' value='" + tdAge.html() + "'/>");
if ($('#txtName').val() == "" || $('#txtPhone').val() == "" || $('#txtEmail').val() == "") {
alert('Please complete the field');
} else {
$('#btnAdd').removeAttr('disabled');
$('.btnSave').attr('disabled','disabled');
$('.btnEdit').removeAttr('disabled');
$('.btnDelete').removeAttr('disabled');
tdFirstName.find('input').attr('disabled', 'true');
tdLastName.find('input').attr('disabled', 'true');
tdAge.find('input').attr('disabled', 'true');
}
$(".btnSave").bind("click", Save);
$(".btnEdit").bind("click", Edit);
$(".btnDelete").bind("click", Delete);
};

Looping through text boxes, using id as a variable?

Basically I'm trying to populate an array with some values in text boxes. I thought I could do it by incrementing though ids, but it isn't working.
Here it is:
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>
Is it possible doing it my method, or will it inevitably not work for whatever reason? Doing some searches it seems jquery might be the way to go, but I'm not sure how to get started with that.
jQuery certainly simplifies things, but it can't do anything that JavaScript can't do, and many amazing websites were built long before jQuery came into existence.
In populateArray(), remove innerHTML here:
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
Should be:
mod[i] = parseInt(document.getElementById(pop).value);
You can simplify the function like this:
function populateArray() {
var i;
for(i = 0 ; i < sections * 3 ; i++) {
mod[i] = parseInt(document.getElementById(i).value);
}
document.getElementById('debug').innerHTML = mod.toString();
}
In addSection(), this wipes out the values of existing input elements:
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
Instead, you should create new input elements and append them.
Here's a rewrite of the function:
var input= document.getElementById('input');
function addSection(){
var inp, i;
sections++;
for(var i = 0 ; i < 3 ; i++) {
inp= document.createElement('input');
inp.type= 'text';
inp.id= identifier++;
input.appendChild(inp);
}
input.appendChild(document.createElement('br'));
} //addSection
In removeSection(), values of all input elements are wiped out.
Instead of rewriting that function, I've done a complete rewrite or your program, without any global variables and without assigning IDs to the input elements.
If you have any questions, I'll update my answer with explanations.
Snippet
function addSection() {
var input= document.getElementById('input'),
sect= document.querySelector('section');
input.appendChild(sect.cloneNode(true));
}
function removeSection() {
var input= document.getElementById('input'),
sects= document.querySelectorAll('section');
if(sects.length > 1) {
input.removeChild(sects[sects.length-1]);
}
}
function calculate() {
var inp= document.querySelectorAll('section input'),
debug= document.getElementById('debug'),
mod= [],
i,
val;
for(i = 3 ; i < inp.length ; i++) {
val= parseInt(inp[i].value);
mod.push(val || 0);
}
debug.innerHTML = mod.toString();
}
section:first-of-type {
display: none;
}
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'>
<section>
<input type="text">
<input type="text">
<input type="text">
</section>
</div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
This version of your script stores the actual elements in an array of sections. That way you can loop through them as you would an array, and alter the contents that way.
Here's a pen of the code: looping through added elements
var sections = [];
var output = document.getElementById('input');
function addSection(){
var section = document.createElement('div');
for (var i = 0; i < 3; i++) {
el = document.createElement('input');
el.type = 'text';
section.appendChild(el);
}
sections.push(section);
output.appendChild(section);
}
function removeSection(){
if (sections.length > 0){
output.removeChild(sections.pop())
}
}
function calculate(){
populateArray();
}
function populateArray(){
for (var i = 0; i < sections.length; i++) {
for (var j = 0; j < sections[i].children.length; j++ ) {
sections[i].children[j].value = (i+1) * (j+2);
}
}
}
If your problem is the NaN, this is because you select an input field and then first try to read its innerHtml before reading its value. Read values of inputs directly.
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>

Increment textarea name to javascript function

So what I am trying to achieve is to increment the points".$id." in the javascript code below starting from 0 like points+n and it would be a dynamic value according to rows in a table. Same for the value 'button".$id."' and all this is because of styled radiobutton labels that are looped etc.
So all I want to do is get rid of all the hardcoded different var txt1 to txt+n, button0 to button+n and points0 to points+n in the JavaScript function.
The real problem here for me is the line: var buttons1 = document.forms[0].button0; how to replace the 0 in button0 to the 'i' in a for loop. Someting like button + i won't work.
Oh and what I'm trying to do is get the values from the radiobuttons to a textarea with one buttongroup and textarea per tablerow.
The code below works for the first 7 rows in my table...
echo "
<td>
<div class='radio'>
<input id='".$temp1."' type='radio' name='button".$id."' onclick='myFunction()' value='4'>
<label for='".$temp1."'></label>
<input id='".$temp2."' type='radio' name='button".$id."' onclick='myFunction()' value='3'>
<label for='".$temp2."'></label>
<input id='".$temp3."' type='radio' name='button".$id."' onclick='myFunction()' value='2'>
<label for='".$temp3."'></label>
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction()' value='1'>
<label for='".$temp4."'></label>
</div>";
echo"<textarea id='points".$id."' name='points".$id."' cols='1' rows='1' ;> </textarea>
</td>
</tr>";
The Javascript function:
function myFunction() {
var txt1 ='';
var txt2 ='';
var txt3 ='';
var txt4 ='';
var txt5 ='';
var txt6 ='';
var txt7 ='';
var buttons1 = document.forms[0].button0;
var buttons2 = document.forms[0].button1;
var buttons3 = document.forms[0].button2;
var buttons4 = document.forms[0].button3;
var buttons5 = document.forms[0].button4;
var buttons6 = document.forms[0].button5;
var buttons7 = document.forms[0].button6;
var buttons8 = document.forms[0].button7;
for (var i = 0; i < 4; i++) {
if (buttons1[i].checked) {
txt1 = txt1 + buttons1[i].value + " ";
}
if (buttons2[i].checked) {
txt2 = txt2 + buttons2[i].value + " ";
}
if (buttons3[i].checked) {
txt3 = txt3 + buttons3[i].value + " ";
}
if (buttons4[i].checked) {
txt4 = txt4 + buttons4[i].value + " ";
}
if (buttons5[i].checked) {
txt5 = txt5 + buttons5[i].value + " ";
}
if (buttons6[i].checked) {
txt6 = txt6 + buttons6[i].value + " ";
}
if (buttons7[i].checked) {
txt7 = txt7 + buttons7[i].value + " ";
}
}
document.getElementById("points0").value = txt1;
console.log(txt1);
document.getElementById("points1").value = txt2;
console.log(txt2);
document.getElementById("points2").value = txt3;
console.log(txt3);
document.getElementById("points3").value = txt4;
console.log(txt4);
document.getElementById("points4").value = txt5;
console.log(txt5);
document.getElementById("points5").value = txt6;
console.log(txt6);
document.getElementById("points6").value = txt7;
console.log(txt7);
}
i think what you need is use the "eval" function in javascript
try the following
var buttons1;
var buttons2;
var buttons3;
var buttons4;
var buttons5;
var buttons6;
var buttons7;
var buttons8;
var j;
for(var i=0;i<8;i++){
j=i+1;
eval("buttons" +j+ " = document.forms[0].button" +i+ ";");
}
If i understood correctly,
Try something like this:
change your onclick as following:
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction(this)' value='1'>
and change function :
function myFunction(button){
var name= button.name;
var id= name.split('button')[1];;
document.getElementById("points"+id).value = buttons.value +" ";
}

how to add Button to a select2 dropdown on a dynamic table

Good day!
I'm doing a Dynamic table which you can add/remove row, and I'm using select2 to search Items on the database via ajax and its working well at the moment, then I want to add another button ("add new item") to my select2's input box. It was also working but when I add another row, the previous rows will have 2 (add new item) buttons on it, and when I add another row something weird is happening on my input box then.
Without adding new rows
After adding new rows
Here is my code:
$(document).ready(function() {
addRow();
});
addRow.js
var rowCount = document.getElementById('tblItemList').rows.length - 1 ;
var rowArrayId = rowCount ;
function addRow(){
var toBeAdded = document.getElementById('toBeAdded').value;
if (toBeAdded=='')
{ toBeAdded = 2; }
else if(toBeAdded>10)
{
toBeAdded = 10;
}
for (var i = 0; i < toBeAdded; i++) {
var rowToInsert = '';
rowToInsert = "<tr><td><input id='itemId"+rowArrayId+"' name='product["+rowArrayId+"][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' /></td>";
$("#tblItemList tbody").append(
rowToInsert+
"<td><textarea readonly name='product["+rowArrayId+"][description]' class='form-control description' rows='1' ></textarea></td>"+
"<input type='hidden' name='product[" + rowArrayId + "][itemId]' id='itemId'>"+
"<td><input type='number' min='1' max='9999' name='product["+rowArrayId+"][quantity]' class='qty form-control' required />"+
"<input id='poItemId' type='hidden' name='product[" + rowArrayId + "][poContentId]'></td>"+
"<td><input type='number' min='1' step='any' max='9999' name='product["+rowArrayId+"][price]' class='price form-control' required /></td>"+
"<td class='subtotal'><center><h3>0.00</h3></center></td>"+
"<input type='hidden' name='product["+rowArrayId+"][delete]' class='hidden-deleted-id'>"+
"<td class='actions'><a href='#' class='btnRemoveRow btn btn-danger'>x</a></td>"+
"</tr>");
var rowId = "#itemId"+rowArrayId;
$(rowId).select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
rowArrayId = rowArrayId + 1;
};
$(".select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
$(".qty, .price").bind("keyup change", calculate);
};
Please Help me find solution for this one, been trying to solve this on my own but I cant get it working. Any suggestions, answers and comments would really be appreciated. Thank you very much and have a good day!
In my case I just added this function
formatNoMatches: function( term ) {
$('.select2-input').on('keyup', function(e) {
if(e.keyCode === 13)
{
$("#modalAdd").modal();
$(".select2-input").unbind( "keyup" );
}
});
return "<li class='select2-no-results'>"+"No results found.<button class='btn btn-success pull-right btn-xs' onClick='modal()'>Add New Item</button></li>";
}

Categories

Resources