remove array items from array list in jquery using javascript - javascript

I want to remove array item on each click. Onclick of get_values button, displays array items in front of delete button/link. I need to remove those item on each click of delete button. It deletes whole item, but i want one by one. Plz help me. I am new to jquery.
<html>
<body>
<div id="array_container">
<label>Name</label>
<input type="text" name="name1" value="" />
<label>State</label>
<input type="text" name="name1" value="" />
<label>Color</label>
<input type="text" name="name1" value="" />
<input type="button" name="get_value" id="get_value" value="Get Value"/>
</div>
<div id="myDiv"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!--<script src="../js/jquery.min.js"></script>-->
<script type="text/javascript">
$("#get_value").click(function ()
{ //causing error here removed the array in name value
var ListOfArray = [];
var option = $('input:text[name=name1]').map(function()
{
return $(this).val();
}).get().join();
$("input:text[name=name1]").val("");
ListOfArray.push(option);
for (var i= 0; i < ListOfArray.length; i++)
{
alert(i); //alert(ListOfArray.length);
var newList = "<a href='#' onClick='removeArray(" + i + ");'return false;> DELETE </a> " + option + " <br>";
alert(newList); //alert(i);
};
document.getElementById('myDiv').innerHTML += newList;
return true;
});
function removeArray(i)
{
var ListOfArray = [];
alert('after removed array.'+i);
ListOfArray.splice(i,1);
var newList = "";
//console.log(ListOfArray);
for (var i = 0; i < ListOfArray.length; i++)
{ //You refer to option here for element, which should be replaced by proper index of array
alert(ListOfArray.length); alert(i);
newList += "<a href='#' onClick='removeArray(" + i + ");'return false;> DELETE </a> " + ListOfArray[i] + " <br>";
alert(i);
};
document.getElementById('myDiv').innerHTML = newList;
return true;
}
</script>
</body>
</html>

Currently ListofArray is local variable to the onclick handler function and removeArray function cant access it from the outer scope. In addition you have declared a new variable inside removeArray . What you need to do is to keep the ListofArray variable as a single instance which is shared by both the functions.
Like
var ListOfArray = [];
$("#get_value").click(function ()
{ //causing error here removed the array in name value
var option = $('input:text[name=name1]').map(function()
{
return $(this).val();
}).get().join();
$("input:text[name=name1]").val("");
ListOfArray.push(option);
for (var i= 0; i < ListOfArray.length; i++)
{
alert(i); //alert(ListOfArray.length);
var newList = "<a href='#' onClick='removeArray(" + i + ");'return false;> DELETE </a> " + option + " <br>";
alert(newList); //alert(i);
};
document.getElementById('myDiv').innerHTML += newList;
return true;
});
function removeArray(i)
{
alert('after removed array.'+i);
ListOfArray.splice(i,1);
var newList = "";
//console.log(ListOfArray);
for (var i = 0; i < ListOfArray.length; i++)
{ //You refer to option here for element, which should be replaced by proper index of array
alert(ListOfArray.length); alert(i);
newList += "<a href='#' onClick='removeArray(" + i + ");'return false;> DELETE </a> " + ListOfArray[i] + " <br>";
alert(i);
};
document.getElementById('myDiv').innerHTML = newList;
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="array_container">
<label>Name</label>
<input type="text" name="name1" value="" />
<label>State</label>
<input type="text" name="name1" value="" />
<label>Color</label>
<input type="text" name="name1" value="" />
<input type="button" name="get_value" id="get_value" value="Get Value"/>
</div>
<div id="myDiv"></div>

Related

Calling multiple functions with code within fails to call both, only calls the first one

Trying to call multiple functions fails.
it only calls the first one, not the second, I mean it has to call both of them.
I use native Javascript then JQuery but still failling.
When I take out the code and just leave the alert("") message, it successfully calls multiple functions. The problem is my functions have to contain codes, not only simple alert statement.
I tried various example from Search but still giving me the same issue which is when I take out the code and leave only the alert message, it works perfect.!!!
<b>Number of items</b> (between 2 and 50):
<input type="number" name="numbItem" min="2" max="50" id="numbItem"> &nbsp&nbsp
<button id='createItem' type="button">Create</button>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
document.getElementById("createItem").onclick = function()
{
var numItems= document.getElementById("numbItem").value;
//alert (price);
//alert (numItems + " items created.")
if (numItems < 2)
{
alert("Can't create just 1 Item;" + "\n" + "Please make sure to enter a number betwen 2 and 50.");
document.body.innerHTML = ""; // Clear Screen
document.location.reload(); // Refresh Page
}
else if (numItems > 50)
{
alert("Can't create more than 50 Items;" + "\n" + "Please make sure to enter a number betwen 2 and 50.");
document.body.innerHTML = ""; // Clear Screen
document.location.reload(); // Refresh Page
}
else
{
alert(numItems + " Items being created. . .");
}
};
</script>
<div id=userForms></div>
<br>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="sumValue" id="sumValueId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Sum" id="btnSumValueId">
&nbsp&nbsp<input type="text" name="sumTaxe" id="sumTaxeId" readonly style="background:#bdf584" size="13"> <input type="submit" value="Sum" id="btnSumTaxeId">
&nbsp&nbsp&nbsp&nbsp<input type="submit" value="Get Totals" id="btnGetTotals" style="width: 140px; position: absolute; left: 550x;">
<br><br>Total Monthly Expenditure&nbsp&nbsp<input type="text" name="totalExpend" id="totalExpValueId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Total" id="btnTotalExpValueId">
<br><br>Effective Tax Rate as %&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="EffectivTaxRate" id="EffectivTaxRateId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Total" id="btnEffectivTaxRateId">
<script type="text/javascript">
$( document ).ready(function()
{
console.log( "ready!" );
$( "#createItem" ).click(function() {
var totalRows = $('#numbItem').val();
var formHtml = '';
for (var i = 1; i <= totalRows; i++)
{
formHtml += ' <input type="text" name="item'+i+'" placeholder="E.g.: Gross Salary" /> <input type="text" name="value'+i+'" placeholder="E.g.: 12000" id="ValueId'+i+'"/> <input type="text" name="tax'+i+'" value="" readonly style="color:#f00;background:#ccc" id="TaxeId'+i+'"> <input type="number" name="vat'+i+'" min="0" max="100" id="VatId'+i+'"> <input name="btnItem'+i+'" value="Calculate" type="button" id="btnCalcId'+i+'"><br><br>';
}
$('#userForms').html(formHtml);
});
});
$('#btnGetTotals').bind('click', function() { student(); });
$('#btnGetTotals').bind('click', function() { calculate(); });
function calculate(){
//alert("Good Morning");
//alert('FRONT !!!');
var total = 10;
for( var i = 3; i <= 50; i++ )
{
var val = parseInt(document.getElementById("ValueId" + i).value);
//alert(document.getElementById("ValueId" + i).value);
document.getElementById("ValueId" + i).value;
if(val>0)
{
total += val;
}
document.getElementById("sumValueId").value = total;
}
}
function student(){
//alert("Hi my name is Sunny");
//alert('FRONT !!!');
var total1 = 55;
for( var i1 = 2; i1 <= 50; i1++ )
{
var val1 = parseInt(document.getElementById("TaxeId" + i1).value);
//alert(document.getElementById("ValueId" + i).value);
document.getElementById("TaxeId" + i1).value;
if(val1>0)
{
total1 += val1;
}
document.getElementById("sumTaxeId").value = total1;
}
}
</script>
</body>
The error is because you cannot use class as a function name.
Convert it to classX or anything else it will work.
Example:
$('#btnGetTotals').bind('click', function() { classX(); });
$('#btnGetTotals').bind('click', function() { student(); });
function classX(){
alert("Good Morning");
}
function student(){
alert("Hi my name is Test");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnGetTotals">
GO
</button>
Update
It is basic to know that you cannot use reserved keywords to name your functions or variables:
See the list of reserved keywords at:
http://www.javascripter.net/faq/reserved.htm
Posting as a new answer because you modified the code after my previous answer:
Several Pointers:
To give spaces use in place of &nbsp
In place of using two bind functions you can call a single one like so:
See below:
$('#btnGetTotals').bind('click', function() {
student();
calculate();
});
You are getting an error in the following code in both of your functions:
for( var i = 3; i <= 50; i++ )
{
var val = parseInt(document.getElementById("ValueId" + i).value);
}
What this does is it iterates from 3 or 2 upto 50 which is wrong as there are not 50 elements if the user selects only 2.
Thus giving you an error:
Cannot read property 'value' of null
So you should enclose your appended code in a common div and then run the loop upto its length like so:
for (var i = 1; i <= totalRows; i++)
{
formHtml += '<div class="newFORM"> <input type="text" name="item'+i+'" placeholder="E.g.: Gross Salary" /> <input type="text" name="value'+i+'" placeholder="E.g.: 12000" id="ValueId'+i+'"/> <input type="text" name="tax'+i+'" value="" readonly style="color:#f00;background:#ccc" id="TaxeId'+i+'"> <input type="number" name="vat'+i+'" min="0" max="100" id="VatId'+i+'"> <input name="btnItem'+i+'" value="Calculate" type="button" id="btnCalcId'+i+'"><br><br></div>';
}
Notice the class newFORM ...
Now whenever I run the loop it should be less than the length of all the classes:
for( var i = 1; i <= $('.newFORM').length; i++ )
{
var val = parseInt(document.getElementById("ValueId" + i).value);
//alert(document.getElementById("ValueId" + i).value);
document.getElementById("ValueId" + i).value;
if(val>0)
{
total += val;
}
document.getElementById("sumValueId").value = total;
}
Hope that helps:
See the demo now:
<p><h3>Budget Calculator TEST [ver 1.0]</h3>**********************************</p>
<b>Number of items</b> (between 2 and 50):
<input type="number" name="numbItem" min="2" max="50" id="numbItem"> &nbsp&nbsp
<button id='createItem' type="button">Create</button>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
document.getElementById("createItem").onclick = function()
{
var numItems= document.getElementById("numbItem").value;
//alert (price);
//alert (numItems + " items created.")
if (numItems < 2)
{
alert("Can't create just 1 Item;" + "\n" + "Please make sure to enter a number betwen 2 and 50.");
document.body.innerHTML = ""; // Clear Screen
document.location.reload(); // Refresh Page
}
else if (numItems > 50)
{
alert("Can't create more than 50 Items;" + "\n" + "Please make sure to enter a number betwen 2 and 50.");
document.body.innerHTML = ""; // Clear Screen
document.location.reload(); // Refresh Page
}
else
{
alert(numItems + " Items being created. . .");
}
};
</script>
<div id=userForms></div>
<br>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="sumValue" id="sumValueId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Sum" id="btnSumValueId">
&nbsp&nbsp<input type="text" name="sumTaxe" id="sumTaxeId" readonly style="background:#bdf584" size="13"> <input type="submit" value="Sum" id="btnSumTaxeId">
&nbsp&nbsp&nbsp&nbsp<input type="submit" value="Get Totals" id="btnGetTotals" style="width: 140px; position: absolute; left: 550x;">
<br><br>Total Monthly Expenditure&nbsp&nbsp<input type="text" name="totalExpend" id="totalExpValueId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Total" id="btnTotalExpValueId">
<br><br>Effective Tax Rate as %&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="EffectivTaxRate" id="EffectivTaxRateId" readonly style="background:#bdf584" size="13">
<input type="submit" value="Total" id="btnEffectivTaxRateId">
<script type="text/javascript">
$( document ).ready(function()
{
console.log( "ready!" );
$( "#createItem" ).click(function() {
var totalRows = $('#numbItem').val();
var formHtml = '';
for (var i = 1; i <= totalRows; i++)
{
formHtml += '<div class="newFORM"> <input type="text" name="item'+i+'" placeholder="E.g.: Gross Salary" /> <input type="text" name="value'+i+'" placeholder="E.g.: 12000" id="ValueId'+i+'"/> <input type="text" name="tax'+i+'" value="" readonly style="color:#f00;background:#ccc" id="TaxeId'+i+'"> <input type="number" name="vat'+i+'" min="0" max="100" id="VatId'+i+'"> <input name="btnItem'+i+'" value="Calculate" type="button" id="btnCalcId'+i+'"><br><br></div>';
}
$('#userForms').html(formHtml);
});
});
$('#btnGetTotals').bind('click', function() { student(); });
$('#btnGetTotals').bind('click', function() { calculate(); });
function calculate(){
alert("Good Morning");
//alert('FRONT !!!');
var total = 10;
for( var i = 1; i <= $('.newFORM').length; i++ )
{
var val = parseInt(document.getElementById("ValueId" + i).value);
//alert(document.getElementById("ValueId" + i).value);
document.getElementById("ValueId" + i).value;
if(val>0)
{
total += val;
}
document.getElementById("sumValueId").value = total;
}
}
function student(){
alert("Hi my name is Sunny");
//alert('FRONT !!!');
var total1 = 55;
for( var i1 = 1; i1 <= $('.newFORM').length; i1++ )
{
var val1 = parseInt(document.getElementById("TaxeId" + i1).value);
//alert(document.getElementById("ValueId" + i).value);
document.getElementById("TaxeId" + i1).value;
if(val1>0)
{
total1 += val1;
}
document.getElementById("sumTaxeId").value = total1;
}
}
</script>

I want to remove an array item when generated check box checked

I made a todolist which is taking value from input and add an item from array so when the given value shown in page i want to remove an item form array whn checkbox checked.
Html part :
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
javascript part:
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div><input id='box' onClick='remove()' type='checkbox' /><label>" + data[i] + "</label></div>";
}
}
function remove() {
var check = document.getElementById('box').value;
for ( var i in list) {
if (list[i]!= check) {
}
}
}
Try this with pure javascript :
Array.splice and Array.indexof()
Add with checkbox inside the label tag.
And click event change with remove(this).Then easly find the label
text and match with list array.
contain.innerHTML +="<div><label><input id='box' onClick='remove(this)' type='checkbox' />" + data[i] +
"</label></div>";
}
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div><label><input id='box' onClick='remove(this)' type='checkbox' />" + data[i] +
"</label></div>";
}
}
function remove(that) {
var check = that.parentElement.textContent;
//that.remove() if you need remove clicked box
for ( var i in list) {
if (list[i] == check) {
list.splice(list.indexOf(check),1);
}
}
console.log(list)
}
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div id='remove" + i + "'><label for='box" + i + "'><input id='box" + i + "' onClick='remove(" + i + ")' type='checkbox' />" + data[i] + "</label></div>";
}
}
function remove(targetId) {
var check = document.getElementById('box' + targetId).checked;
if(check){
console.log('Remove box' + targetId);
document.getElementById('remove' + targetId).innerHTML='';
}
}
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
I just modified your JavaScript to pass an ID with a number to set each label apart from each other..

Collect value of all input with same Class dinamically per milliseconds(setInterval), and wrap it - Using Jquery

I try to build form like this jsfiddle.net/pu3antasyah/5au979ck/ . Collect multiple value from other textarea and input in to one textarea.
Bytheway how to collect all input value dinamically from all input with .step class like this >> <input class="step" /> and wrap it using <li /> . send to <textarea id="collectallfieldtosave texarea" />
$(function(){
var scntDiv = $('#steparea');
var i = $('#steparea p').size() + 1;
$('#addinput').live('click', function() {
$('<p><input class="step-'+ i +'" value="step '+ i +'">remove</p><br/><br/>').appendTo(scntDiv);
i++;
return false;
});
$('.remove').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
window.setInterval(function(){
var
space = ' ',
line = '\n',
summary = $('.summary').val(),
theyield = $('#yield').val(),
IngredientsTitle = '<b>Ingredients for (<span class="yield">' +space+ theyield +'</span>)</b>',
step = '<li>' + $('.step').val() + '</li>';
$('#collectallfieldtosave').val( summary + line + line + IngredientsTitle + line + line + '<ol>' + step + '</ol>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea name="summary" rows="7" class="summary"></textarea>
<br/><br/>
<input id="yield" value="1 person">
<br/><br/>
<div id="steparea">
<p><input class="step" value="step 1">remove</p>
<br/><br/>
</div>
add more step
<br/><br/>
<br/><br/>
<textarea id="collectallfieldtosave" name="nameoffield" rows="15" cols="70" placeholder=".." class="usp-textarea"></textarea>
You shouldn't be using live here. Use on and listen to events on #steparea (live is deprecated) And as of your solution you have to iterate using $.each() jquery fn
$(function(){
var scntDiv = $('#steparea');
var i = $('#steparea p').size() + 1;
$('#addinput').live('click', function() {
$('<p><input class="step" value="step '+ i +'">remove<br/><br/></p>').appendTo(scntDiv);
i++;
return false;
});
$('.remove').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
function findSteps(what){
var acc = '';
$(what).each(function(){
acc += '<li>'+$(this).val()+'</li>';
});
return acc;
}
window.setInterval(function(){
var
space = ' ',
line = '\n',
summary = $('.summary').val(),
theyield = $('#yield').val(),
IngredientsTitle = '<b>Ingredients for (<span class="yield">' +space+ theyield +'</span>)</b>',
step = findSteps('.step');
$('#collectallfieldtosave').val( summary + line + line + IngredientsTitle + line + line + '<ol>' + step + '</ol>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea name="summary" rows="7" class="summary"></textarea>
<br/><br/>
<input id="yield" value="1 person">
<br/><br/>
<div id="steparea">
<p><input class="step" value="step 1">remove<br/><br/> </p>
</div>
add more step
<br/><br/>
<br/><br/>
<textarea id="collectallfieldtosave" name="nameoffield" rows="15" cols="70" placeholder=".." class="usp-textarea"></textarea>

Make a html unordered list from javascript array

I'm having a bit of a problem. I'm trying to create a unordered list from a javascript array, here is my code:
var names = [];
var nameList = "";
function submit()
{
var name = document.getElementById("enter");
var theName = name.value;
names.push(theName);
nameList += "<li>" + names + "</li>";
document.getElementById("name").innerHTML = nameList;
}
<input id="enter" type="text">
<input type="button" value="Enter name" onclick="submit()">
<br>
<br>
<div id="name"></div>
For example, if I post 2 names, Name1 and Name2 my list looks like this:
•Name1
•Name1,Name2
I want it to look like this:
•Name1
•Name2
If you look at your code, you are only creating one li with all your names as the content. What you want to do is loop over your names and create a separate li for each, right?
Change:
nameList += "<li>" + names + "</li>";
to:
nameList = "";
for (var i = 0, name; name = names[i]; i++) {
nameList += "<li>" + name + "</li>";
}
If you are interested in some better practices, you can check out a rewrite of your logic here: http://jsfiddle.net/rgthree/ccyo77ep/
function submit()
{
var name = document.getElementById("enter");
var theName = name.value;
names.push(theName);
document.getElementById("name").innerHTML = "";
for (var I = 0; I < names.length; I++)
{
nameList = "<li>" + names[I] + "</li>";
document.getElementById("name").innerHTML += nameList;
}
}
You are using an array, when you print an array JavaScript will show all the entries of the array separated by commas. You need to iterate over the array to make it work. However you can optimize this:
var names = [];
function displayUserName()
{
var theName = document.getElementById("enter").value;
if (theName == "" || theName.length == 0)
{
return false; //stop the function since the value is empty.
}
names.push(theName);
document.getElementById("name").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
}
<input id="enter" type="text">
<input type="button" value="Enter name" onclick="displayUserName()">
<br>
<br>
<div id="name"><ul></ul></div>
In this example the HTML is syntactically correct by using the UL (or unordered list) container to which the lis (list items) are added.
document.getElementById("name").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
This line selects the div with the name: name and its first child (the ul). It then appends the LI to the list.
As #FelixKling said: avoid using reserved or ambiguous names.
<div>
<label for="new-product">Add Product</label><br /><br /><input id="new-product" type="text"><br /><br /><button>Add</button>
</div>
<div>
<ul id="products">
</ul>
<p id="count"></p>
</div>
var products = [];
var productInput = document.getElementById("new-product");
var addButton = document.getElementsByTagName("button")[0];
var productListHtml = "";
var abc = 0;
addButton.addEventListener("click", addProduct);
function addProduct() {
products.push(productInput.value);
productList();
}
function productList() {
productListHtml += "<li>" + products[abc] + "</li>";
document.getElementById("products").innerHTML = productListHtml;
abc++;
}

userHow to collect the values from html form for variable input values in google app script?

I am creating the input fields with the add more feature which are then sent to the google script file, how can I collect the values of the fields as shown in code I implemented below..
google app script file
code.gs
function getFormValue(formValue) {
var myarr= {};
var count = formValue.count;
for(var g = 1; g<=count; g++ )
{
user["I"+g] = formValue.user+g; // error, what to do here
}
// code
}
index.html
<script>
$(document).ready(function() {
var counter = 2;
$("#addMoreUser").click(function() {
if (counter > 7) {
alert("Only 7 Users are allowed");
return false;
}
var newRowDiv = $(document.createElement('div'))
.attr("id", 'rowDiv' + counter);
newRowDiv.after().html('<div class="row" id="rowDiv" ><div class="col-md-3"><input class="form-control" placeholder="user'+ counter +' " name="user'+ counter +'" id="user'+ counter +'" type="text" value=""></div></div>');
newRowDiv.appendTo("#rowDivGroup");
$("#count").val(counter);
counter++;
});
$( "#submitForm" ).submit(function() {
google.script.run.withSuccessHandler(function(ret){
console.log(ret);
}).getFormValue(this); //"this" is the form element
});
});
</script
<form class="contact-form" id="myform">
<input type="hidden" value="1" name="count" id="count">
<div id="rowDivGroup">
<div class="row" id="rowDiv">
<div class="col-md-3">
<input class="form-control" placeholder="Name of User" name="user1" id="user1" type="text" value=""></div></div></div>
<a class="btn btn-sm btn-flat btn-success btn-rounded" id="addMoreUser">Add More Users</a>
<input type="submit" class="btn btn-flat flat-color btn-rounded btn-sm" id="submitForm" value="Submit Details ">
</form>
This code takes the value of an array, and creates an object:
function getFormValue(formValue) {
formValue = ["someInput1", "someInput2", "someInput3", "someInput4", "someInput5", "someInput6", "someInput7"];
Logger.log('formValue: ' + formValue);
var myarr= {};
var count = formValue.length;
Logger.log('count: ' + count);
var user = {};
for(var g = 1; g<=count; g++ )
{
Logger.log('g: ' + g);
var k = "user"+g;
var userID = "I" + g;
Logger.log("userID: " + userID);
Logger.log("formValue: " + formValue[g-1]);
user[userID] = formValue[g-1];
Logger.log("The property value: " + user[userID]);
}
}
I've run the code, and it works. The values for the array are hard coded for testing purposes.

Categories

Resources