Good evening. I am new to JavaScript and I need help with my mini-project and I have only one issue here and it is in the this.Add = function ().
It works properly when I enter a duplicate value from my list therefore it displays an alert that no dupes are allowed. But... when I enter a unique value, it only adds up the last element present (Wash the dishes) from myTasks list. instead of the one I recently entered and the list goes on adding the same ones. Did I just misplace something?
This is my final activity yet and I want to finish it to move to the next function. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tasks CRUD</title>
<style>
#tasks{
display: none;
}
</style>
</head>
<body>
<center>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-task" placeholder="Add another card">
<input type="submit" value="Add">
</form>
<div id="tasks" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-task">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Name</th>
</tr>
<tbody id="myTasks">
</tbody>
</table>
</center>
<script>
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
if (task ) {
for(task of this.myTasks)
{
var ctr = 0;
if(document.getElementById("add-task").value == task){
ctr = 1;
break;
}
}
if(ctr == 1)
{
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task.trim());
// Reset input value
el.value = '';
// Dislay the new list
this.FetchAll();
}
}
};
this.Edit = function (item) {
var el = document.getElementById('edit-task');
// Display value in the field
el.value = this.myTasks[item];
// Display fields
document.getElementById('tasks').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
// Get value
var task = el.value;
if (task) {
// Edit value
self.myTasks.splice(item, 1, task.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item) {
// Delete the current row
this.myTasks.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput() {
document.getElementById('tasks').style.display = 'none';
}
</script>
</body>
</html>
In your for loop:
for (task of this.myTask) {
}
You are not declaring a new task variable, but instead assigning to the outer task variable, hence the repeated addition of tasks already in your list.
You can declare a new variable in the for scope like so:
for (const task of this.myTask) {
}
Your HTML as it is.
And your Javascript goes like below. You have a bug while checking if the task already exists in the array. As you're comparing string value either use simple for loop with triple equals or do as i have attached below.
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
console.log(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
console.log(task);
if (task ){
var arrayContainsTask = (this.myTasks.indexOf(task) > -1);
if(arrayContainsTask == true){
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task);
// Reset input value
el.value = '';
}
// Dislay the new list
this.FetchAll();
}
}
}
Related
I made a selectBox which had its range of values from a Google Sheet Column. I also want to take an Integer input value from the user and then write this value in a specific cell according to option taken from selectBox. The html link does not show the integer response box. Is it possible to do the above plan in a while loop? Would appreciate any ideas and correction of code
function doGet() {
var ap = SpreadsheetApp.openByUrl("Gsheet URL here");
var ui = SpreadsheetApp.getUi();
var user = ui.prompt("Put down a number");
var result = result.getSelectedButton();
var sheet = ap.getSheetByName("lv");
var values = sheet.getRange("A2:A10").getValues();
var options = values.map(function(row)
{
#To show show the selected option??
var item = options.getSelecteditem();
if (item === A3)
{
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var a1 = cell.getA3Notation();
var val = cell.getValue();
SpreadsheetApp.getUi().alert("Ur value is "+a1+" value is "+val);
}
{
return '<option value="' + row[0] + '">' + row[0] + '</option>';
});
var html = '<form onSubmit="handleSubmit(this)"> Type of Cuisine' + options.join('') + '</select></form>';
return HtmlService.createHtmlOutput(html);
}
Using an Html Dialog to Control User Inputs
Not sure what you wanted so here's a complete example I whipped up for you.
Code.gs:
function processInput(obj) {
Logger.log(JSON.stringify(obj));
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
const [min,max,locs] = sh.getRange('B1:B3').getValues().flat();
Logger.log('min: %s max: %s locs: %s',min,max,locs)
const lA = locs.split(',');
if(obj.int > max) {
obj.msg = "Too High Try Again";
return obj;
} else if (obj.int < min) {
obj.msg = "To Low Try Again";
return obj;
} else if (!~lA.indexOf(obj.loc)) {
obj.msg = "Invalid Location";
return obj;
} else {
sh.getRange(obj.loc).setValue(obj.int);
obj.msg = "Complete";
return obj;
}
}
Following function Launches the dialog:
function launchInputDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'),"Enter Input");
}
html:
<!DOCTYPE html>
<html>
<head>
</head>
<style>input {margin: 2px 5px 2px 0;}</style>
<body>
<form>
<input type="text" id="in1" placeholder="Enter an integer" />
<br /><input type="text" id="in2" placeholder="Enter a location" />
<br /><input type="button" value="Process" onClick="processinput();" />
</form>
<div id="msg"></div>
<script>
function processinput() {
document.getElementById("msg").innerHTML = '';
let v1 = parseInt(document.getElementById('in1').value);
let v2 = document.getElementById('in2').value;
let obj = {int:v1,loc:v2,msg:''};
google.script.run
.withSuccessHandler(robj => {
console.log(JSON.stringify(robj))
if(robj.msg == "Complete") {
document.getElementById("msg").innerHTML = `Value: ${robj.int} Location: ${robj.loc} Try Again`;
document.getElementById("in1").value = '';
document.getElementById("in2").value = '';
} else {
document.getElementById("msg").innerHTML = robj.msg;
}
})
.processInput(obj);
}
</script>
</body>
</html>
Short Demo:
This version uses a <select> tag to allow the user to determine where the data will be loaded
GS:
function doPost(e) {
Logger.log(e.postData.contents);
Logger.log(e.postData.type);
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet1");
let data = JSON.parse(e.postData.contents);
sh.getRange(data.loc).setValue(data.id)
}
function sendData(obj) {
const url = ScriptApp.getService().getUrl();
const params = { "contentType": "application/json", "payload": JSON.stringify(obj), "muteHttpExceptions": true, "method": "post", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
UrlFetchApp.fetch(url, params);
}
function displayError(msg) {
SpreadsheetApp.getUi().alert(msg);
}
function launchMyDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'), 'My Dialog');
}
function getSelectOptions() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName('Options');
var rg = sh.getDataRange();
var vA = rg.getValues();
var options = [];
for (var i = 0; i < vA.length; i++) {
options.push(vA[i][0]);
}
return vA;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<input type="text" id="txt1" name="id" placeholder="Enter Numbers only"/>
<select id="sel1" name="loc"></select>
<input type="button" value="submit" onClick="processForm(this.parentNode);" />
</form>
<script>
function processForm(obj) {
console.log(obj.id.value);
if(obj.id.value.match(/[A-Za-z]/)) {
google.script.run.displayError("Invalid Characters Found in id field");
} else {
google.script.run.sendData(obj);
}
}
window.onload = function() {
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
}
function updateSelect(vA) {
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<vA.length;i++) {
select.options[i] = new Option(vA[i],vA[i]);
}
}
</script>
</body>
</html>
Demo:
I have a initial value of 10000 and I want to add or substract the initial value depending to the value I input. For example, I click the radio button name Add I want to disable the 2nd textBox. Enter a value into 1st textbox. Add the initial value and the value of textbox1. When I click the 2nd radio button name Minus I want to disable the 1st textBox minus 2nd textbox to initial value. OOP style. When I click the compute button it show the answer and back it to normal so I can choose and enter another number add it to table.
//external script
function Compute(initialNum, numOne, numTwo) {
this._initialNum = initialNum; // 10000
this._numOne = numOne; //input by user
this._numTwo = numTwo; //input by user
this.addNum = function() {
this._initialNum = this._initialNum + this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum = this._initialNum - this._numTwo;
return this._initialNum;
};
}
//JavaScript in <body>
var initialValue = 10000;
var numOne = parseInt(document.getElementById('txtNumOne'));
var numTwo = parseInt(document.getElementById('txtNumTwo'));
var rdoAdd = document.getElementById("rdoAdd").value;
var rdoMinus = document.getElementById("rdoMinus").value;
var tblResult = document.getElementById("tblResult");
function disableTxtAdd() {
if(rdoAdd == "rdoAdd") {
document.getElementById("txtNumTwo").disabled = true;
}
else{
document.getElementById("txtNumTwo").disabled = false;
}
}
function disableTxtMinus() {
if(rdoMinus == "rdoMinus") {
document.getElementById("txtNumOne").disabled = true;
}
else{
document.getElementById("txtNumOne").disabled = false;
}
}
function print() {
var objAccount = new Compute(initialValue, numOne.value, numTwo.value);
var display = "";
if(rdoAdd.checked)
{
display += "<tr>";
display += "<td>" + objAccount.addNum() + "</td>";
display += "<tr>";
tblResult.innerHTML = display;
} else {
display += "<tr>";
display += "<td>" + objAccount.minusNum() + "</td>";
display += "<tr>";
tblResult.innerHTML = display;
}
}
<input name = "operation" type = "radio" id = "rdoAdd" value = "rdoAdd" onclick = "disableTxtAdd()">Add<br><br>
<input name = "operation" type = "radio" id = "rdoMinus" value = "rdoMinus" onclick = "disableTxtMinus()">Minus<br><br>
Deposit:<br><br>
<input type = "text" id = "txtNumOne"><br><br>
Withdraw<br><br>
<input type = "text" id = "txtNumTwo">
<button onclick = "print()">Compute</button><br><br>
<table border = "1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angelica's calculator</title>
<script>
// When the Add button is clicked
function disableTxtAdd() {
document.getElementById("txtNumTwo").disabled = true;
document.getElementById("txtNumOne").disabled = false;
}
// When the Minus button is clicked
function disableTxtMinus() {
document.getElementById("txtNumOne").disabled = true;
document.getElementById("txtNumTwo").disabled = false;
}
// When the Compute button is clicked
function print(){
var initialValue = 10000;
var numOne = document.getElementById('txtNumOne').value;
var numTwo = document.getElementById('txtNumTwo').value;
var tblResult = document.getElementById("tblResult");
var display;
var result;
if(document.getElementById("txtNumTwo").disabled){
// Add input value to 10000
if(Number.isInteger(parseInt(numOne))){
result = initialValue + parseInt(numOne);
}else{
result = "Enter a number";
}
display = "<tr><td>" + result + "</td><tr>";
tblResult.innerHTML = display;
}else if(document.getElementById("txtNumOne").disabled){
// Subtract input from 10000
if(Number.isInteger(parseInt(numTwo))){
result = initialValue - parseInt(numTwo);
}else{
result = "Enter a number";
}
display = "<tr><td>" + result + "</td><tr>";
tblResult.innerHTML = display;
}
// Enable both inputs
document.getElementById("txtNumTwo").disabled = false;
document.getElementById("txtNumOne").disabled = false;
// Empty the inputs
document.getElementById("txtNumTwo").value = "";
document.getElementById("txtNumOne").value = "";
}
</script>
</head>
<body>
<input name="operation" type="radio" id="rdoAdd" value="rdoAdd" onclick="disableTxtAdd()">Add<br><br>
<input name="operation" type="radio" id="rdoMinus" value="rdoMinus" onclick="disableTxtMinus()">Minus<br><br>
Deposit:<br />
<input type="text" id="txtNumOne"><br /><br />
Withdraw<br />
<input type="text" id="txtNumTwo"><br /><br />
<button onclick="print()">Compute</button><br /><br />
<table border="1px" style="border-collapse:collapse";>
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
</body>
</html>
I've created some code that dynamically creates some fields within a SPAN element. One of the fields is a delete icon, that when click runs a function to remove the selected span. Now I want to create a function that simply wipes out all the spans, sounds simple but it breaks after the first one.
This is a sample of my code (modified it for simplicity):
<form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem()
{
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ip = document.createElement("INPUT");
var im = document.createElement("IMG");
var el = document.createElement('SPAN');
ip.setAttribute("type", "text");
ip.setAttribute("value", item)
ip.setAttribute("Name", "text_item_element_" + global_i);
ip.setAttribute("id", "id_item_" + global_i);
ip.setAttribute("style", "width:80px");
im.setAttribute("src", "delete.png");
im.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(ip);
el.appendChild(im);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
In each line for the image I set the onclick event handler to run the function removeSpanElement(parentDiv, childDiv) and it works fine. So to clear them all I'd think I just run the function through an incremental loop, clearItems(), but it stops after removing the first one and I can't figure out why.
You can simply add a new class to the dynamically added span(to make it easy to select them), then remove all the elements with the added class like
var global_i = 0; // Set Global Variable i
function increment() {
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem() {
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ins = document.createElement("INPUT");
var im = document.createElement("IMG");
var el = document.createElement('SPAN');
ins.setAttribute("type", "text");
ins.setAttribute("value", item);
ins.setAttribute("Name", "text_item_element_" + global_i);
ins.setAttribute("id", "id_item_" + global_i);
ins.setAttribute("style", "width:80px");
im.setAttribute("src", "delete.png");
im.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(ins);
el.appendChild(im);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
el.className = 'dynamic'
document.getElementById("myForm").appendChild(el);
}
/* This function only clears 1st span */
function clearItems() {
var spans = document.getElementsByClassName('dynamic');
while (spans.length) {
spans[0].remove();
}
global_i = 0;
}
<form>
<input type='text' id='item' value='' />
<input type="button" value="Add" onclick="addItem()" />
<input type="button" value="Clear All" onclick="clearItems()" />
<span id="myForm"></span>
</form>
You were using a reserved keyword, and you were having a variable undefined. I've edited the code for you. Compare my code with yours to see where are the mistakes.
<form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem(){
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ig = document.createElement("INPUT"); // "in" is a reserved keyword. It can't be used as a variable
var ip = document.createElement("IMG");
var el = document.createElement('SPAN');
ig.setAttribute("type", "text"); // modified
ig.setAttribute("value", item) //
ig.setAttribute("Name", "text_item_element_" + global_i); //
ig.setAttribute("id", "id_item_" + global_i); //
ig.setAttribute("style", "width:80px"); //
ig.setAttribute("src", "delete.png"); // "im" was undefined. You probably wanted to write "in", but it was wrong anyway
ig.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')"); // the same
el.appendChild(ig);
el.appendChild(ig);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
<code> <form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem()
{
try{
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var in_e = document.createElement("INPUT");
var ip_e = document.createElement("IMG");
var el = document.createElement('SPAN');
in_e.setAttribute("type", "text");
in_e.setAttribute("value", item)
in_e.setAttribute("Name", "text_item_element_" + global_i);
in_e.setAttribute("id", "id_item_" + global_i);
in_e.setAttribute("style", "width:80px");
ip_e.setAttribute("src", "delete.png");
ip_e.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(in_e);
el.appendChild(in_e);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}catch(e){alert(e)}
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
</code>
I am currently working on a little recreational Google Apps Script (GAS) for EVE Online and I have hit a brick wall when I am getting my server side functions talking to my client side ones.
HTML:
<form id="frm1" name = "mat_add">
<input width="1000" type="text" name="mat" value="Enter Item Here"><br />
<input type="button" value="Submit" name="mat_sub" onclick= "google.script.run.withSuccessHandler(onSuccess).shortlist(this.parentNode,document.getElementById('spn1').innerHTML)">
</form>
<span id="spn1"><table><tr><td>Type Name</td><td>Type ID</td></tr></table></span>
<script>
function onSuccess(output) {
document.getElementById(output[0]).innerHTML = output[1];
};
</script>
GAS:
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate().setTitle('UMX Web App');
};
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
};
function shortlist(form,table) {
var arr = transpose(htmlToArray(table));
var item = form.mat;
if ( isNaN(item) ) {
var url = 'https://www.fuzzwork.co.uk/api/typeid2.php?format=xml&typename=' + item.toString();
} else {
var url = 'https://api.eveonline.com/eve/TypeName.xml.aspx?ids=' + item.toString();
};
var xml = UrlFetchApp.fetch(url).getContentText();
var document = XmlService.parse(xml);
var name = document.getRootElement().getChild('result').getChild('rowset').getChild('row').getAttribute('typeName').getValue();
if ( arr[0].indexOf(name) == -1 && name != 'Unknown Type' && name != 'bad item' ) {
arr[0].push(name);
arr[1].push(document.getRootElement().getChild('result').getChild('rowset').getChild('row').getAttribute('typeID').getValue());
};
var str = arrayToHTML(transpose(arr));
return ['spn1',str]
};
function arrayToHTML(arr) {
var i = 0;
var j = 0;
var str = '<table>';
while ( i < arr.length ) {
str = str + '<tr>';
while ( j < arr[i].length ) {
str = str + '<td>' + arr[i][j] + '</td>';
j += 1
};
str = str + '</tr>';
j = 0;
i += 1
};
str = str + '</table>';
return str
};
function htmlToArray(str) {
var arr1 = str.replace(/<tr>/g,'</tr>').split('</tr>');
var arr2 = [];
var i = 1;
var j = 1;
var x = [];
while ( i < arr1.length ) {
arr2.push([]);
x = arr1[i].replace(/<td>/g,'</td>').split('</td>');
while ( j < x.length ) {
arr2[arr2.length - 1].push(x[j]);
j += 2
};
j = 1;
i += 2
};
return arr2
};
function transpose(input) {
var output = [];
var i = 0;
var j = 0;
while ( i < input[0].length ) {
output.push([]);
while ( j < input.length ) {
output[i].push(input[j][i]);
j += 1
};
j = 0;
i += 1
};
return output
};
function direct(input) {
return input
}
The problem seems to be on the submit button because everything else is working fine. I have been looking for a workaround but that submit button is the only point of entry I can get and it will not accept more than one variable.
The problem seems to be on the submit button because everything else is working fine. I have been looking for a workaround but that submit button is the only point of entry I can get and it will not accept more than one variable.
Let's focus on this, and ignore all the irrelevant code. Basic question: how to get multiple inputs from a form to a server-side GAS function?
This example will demonstrate communication of the form object to the server, by throwing an error that contains all the received parameters. An errorHandler on the client side will alert with the received error message.
Index.html
<form id="frm1" name = "mat_add">
<input width="1000" type="text" name="mat" placeholder="Enter Item Here" /><br />
<input width="1000" type="text" name="mat2" placeholder="Enter Quantity Here" /><br />
<input type="button" value="Submit" name="mat_sub" onclick="google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(onFailure)
.shortlist(this.parentNode)" />
</form>
<script>
function onSuccess(output) {
document.getElementById(output[0]).innerHTML = output[1];
};
function onFailure(error) {
alert( error.message );
}
</script>
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate().setTitle('UMX Web App');
};
function shortlist(input) {
reportErr(JSON.stringify(input,null,2))
}
function reportErr(msg) {
throw new Error( msg );
}
Run this webapp, and here's your result:
The two named input elements, mat and mat2 were communicated to the server function shortlist() via the this.parent parameter. Since the button invoking this.parent in its clickHandler is contained in the frm1 form, all input elements of that form were included, and may be referenced on the server side as named properties of the input parameter of shortlist(). (NOT as array elements.)
The upshot of this is that your shortlist() function can be modified thusly:
function shortlist(input) {
var item = input.mat;
if ( isNaN(item) ) {
var url = 'https://www.fuzzwork.co.uk/api/typeid2.php?format=xml&typename=' + item;
} else {
var url = 'https://api.eveonline.com/eve/TypeName.xml.aspx?ids=' + item.toString();
};
...
I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>