Passing checkbox array to GAS? - javascript

I am using Google App Script to create an HTML sidebar in Sheets. I want to have several checkboxes to select and pass the values back to GAS, preferably as an array. I have been looking up solutions and was using this as a guide. Here is my GAS code:
function showSidebar() {
var array = ["A","B","C","D","E"];
var html = HtmlService.createTemplateFromFile('page');
html.cols = array;
var html = html.evaluate().setTitle('Example');
SpreadsheetApp.getUi()
.showSidebar(html);
}
function displayToast(columns) {
SpreadsheetApp.getActive().toast("Output: " + columns);
}
The toast is there to test my setup, but it doesn't display when I click the submit button.
Here is the 'page' HTML:
<body>
<p>Which columns should be included in the email?</p>
<? for(var i = 0; i < cols.length; i++) { ?>
<input type="checkbox" name="col" id="<?= cols[i] ?>" value="<?= cols[i] ?>">Col
<?= cols[i] ?></input>
<? } ?><br>
<button id="btn">Submit</button> <br>
</body>
<script>
document.getElementById('btn').onclick = function() {
var markedCheckbox = document.getElementsByName('col');
google.script.run.displayToast(markedCheckbox);
}
</script>
The sidebar displays correctly, but I just can't get the checkbox values to pass over to the GAS side.
TIA.

You can't pass the HTML element to Apps Script. You have to send only the values:
document.getElementById('btn').onclick = function() {
var markedCheckbox = Array.from(document.getElementsByName('col'))
.filter(x => x.checked)
.map(x => x.value)
google.script.run.displayToast(markedCheckbox);
}

Related

Sending an email with PHP/Javascript submit button

I will try and be brief. When a user selects items in a checkbox, I want them to be able to press a submit button and it will send an email of the ingredients to a static email address. I am trying to store the values of the check boxes in an array called finalOrder, and have that array in the contents of the email.
I am fairly new to both languages, can I use the submit button to call the PHP code? Is the PHP written correctly? I am not too sure how to go about this.
Here is what I have so far.
<div>
<input type="checkbox" name="foodType" data-name="Chicken Thighs"> <label
for="chickenThighs">Chicken Thighs</label>
<input type="checkbox" name="foodType" data-name="Chicken Breast"> <label
for="chickenBreast">Chicken Breast</label>
<input type="checkbox" name="foodType" data-name="Chicken Leg"> <label
for="chickenLeg">Chicken Leg</label>
</div>
<div id='results'>
</div>
<script type="text/javascript">
var finalOrder = [];
document.querySelectorAll('input[name=foodType]').forEach(elem => {
elem.addEventListener('change', updateList);
});
function buildList ()
{
let list = '<ul>';
finalOrder.forEach(str => {
list += "<li>" + str + '</li>';
});
list += '</ul>';
return list;
}
function updateList ()
{
finalOrder = []; // Reset this array so that we can populate it with the new checkbox answers.
document.querySelectorAll('input[name=foodType]').forEach(v => {
if (v.checked) {
finalOrder.push(v.dataset.name);
}
});
document.querySelector('#results').innerHTML = buildList();
}
</script>
<input type="submit" value="Submit">
<?php
// the message
$msg = finalOrder;
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap(finalOrder($msg,70));
// send email
mail("my#email.com","New Order",$msg);
?>
There is one thing, missing so far.
A form tags to help post the data for the server for processing by PHP language so the file has to be saved as a PHP file and HTML. In the snippet I saved it as thisFile.php.
You can also consider the approach stated by #jaaba
<div>
<form method="POST" action="thisFile.php">
<input type="checkbox" name="foodType" data-name="Chicken Thighs"> <label
for="chickenThighs">Chicken Thighs</label>
<input type="checkbox" name="foodType" data-name="Chicken Breast"> <label
for="chickenBreast">Chicken Breast</label>
<input type="checkbox" name="foodType" data-name="Chicken Leg"> <label
for="chickenLeg">Chicken Leg</label>
</div>
<input type="submit" value="Submit">
</form>
<div id='results'>
</div>
<script type="text/javascript">
var finalOrder = [];
document.querySelectorAll('input[name=foodType]').forEach(elem => {
elem.addEventListener('change', updateList);
});
function buildList ()
{
let list = '<ul>';
finalOrder.forEach(str => {
list += "<li>" + str + '</li>';
});
list += '</ul>';
return list;
}
function updateList ()
{
finalOrder = []; // Reset this array so that we can populate it with the new checkbox answers.
document.querySelectorAll('input[name=foodType]').forEach(v => {
if (v.checked) {
finalOrder.push(v.dataset.name);
}
});
document.querySelector('#results').innerHTML = buildList();
}
</script>
<?php
// the message
$msg = finalOrder;
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap(finalOrder($msg,70));
// send email
mail("my#email.com","New Order",$msg);
?>

Get the Checked box input values using Jquery in CodeIgniter using Mysql

I want to display checked checkbox value with input box value when i clicking button in codeigniter. Checked checkbox value has deen displayed correctly using join function. but input values is not showing. In my code, when i clicking button all input text values are displayed. my problem to display only checked checkbox input value using join function.
Controller code:
public function unpaid()
{
$basicUrl=$this->config->item("basicUrl");
$query=$this->db->query("SELECT aa.id as id,customer_type_id,start_time,close_time,dd.name as customer_name,bb.name as vehicle_name,cc.name as driver_name,other_expensive,paid_amount,payment_date,payment_mode,payment,tour_file,DATE_FORMAT(aa.created_date, '%d/%m/%Y') as created_date FROM ".$this->tbl." as aa
left join vehicle as bb on aa.vehicle_id=bb.id
left join driver as cc on aa.driver_id=cc.id
left join tbl_customer as dd on aa.customer_id=dd.id
order by aa.id desc");
$result=array();
if($query->num_rows()){
$i=1;
foreach($query->result() as $row){
$result_row=array();
$result_row[]='<input type="checkbox" name="unpaid_id[]" id="unpaid_id" value="'.$row->id.'" />';
$result_row[]=$row->created_date;
$result_row[]=$i;
$result_row[]=$row->customer_name;
$result_row[]=$row->payment;
$result_row[]='<input type="text" name="paid_amount[]" id="paid_amount" value="'.$row->paid_amount.'" />';
$result_row[]=$row->payment_date;
$result_row[]='<input type="text" name="payment_mode[]" id="payment_mode" value="'.$row->payment_mode.'" />';
$result[]=$result_row;
$i++;
}
}
My view code:
<input type="button" class="btn btn-primary" id="save_value" name="save_value" value="Save" />
<script>
$(document).ready(function() {
$('#save_value').click(function(){
var favorite = [];
var favorite1 = [];
var unpaid_id = [];
var paid_amount = [];
var payment_mode = [];
$.each($("input[ type='checkbox']:checked"), function(){
unpaid_id.push($(this).val());
});
var unpaid_id = unpaid_id.join(",");
alert(unpaid_id);
$.each($("input[ id='paid_amount']"), function(){
paid_amount.push($(this).val());
});
alert(paid_amount.join(","));
var paid_amount = paid_amount.join(",");
});
</script>
Thanks #
use the class in place of id
$.each($("input[class='paid_amount']"), function(){
paid_amount.push($(this).val());
});

How to insert JSON Array into database

I'm using dropdown when selected first dropdown, based on first dropdown selected it will show second dropdown. Each dropdown have data from database and the problem is i want to insert it into new table on database based on dropdown selected.
All the code on the same page, this is the php.
<?php
$sql= mysql_query("SELECT KodeMapel,NamaTema FROM mapel");
while ($row = mysql_fetch_array($sql))
{
$tema[] = array("KodeMapel" => $row['KodeMapel'], "val" => $row['NamaTema']);
}
$query = mysql_query("SELECT KodeMapel, Subtema FROM subtema");
while ($row = mysql_fetch_array($query))
{
$subtema[$row['KodeMapel']][] = array("KodeMapel" => $row['KodeMapel'], "val" => $row['Subtema']);
}
$jsonTema = json_encode($tema);
$jsonSubTema = json_encode($subtema);
?>
This is the form, included javascript on it. Inside the javascript there's php code.
<script type='text/javascript'>
<?php
echo "var tema = $jsonTema;";
echo "var subtema = $jsonSubTema;";
?>
function loadtema(){
var select = document.getElementById("PilihTema");
select.onchange = updateSubTema;
for(var i = 0; i < tema.length; i++){
select.options[i] = new Option(tema[i].val,tema[i].KodeMapel);
}
}
function updateSubTema(){
var PilihTema = this;
var idtema = this.value;
var PilihSubtema = document.getElementById("PilihSubtema");
PilihSubtema.options.length = 0; //delete all options if any present
for(var i = 0; i < subtema[idtema].length; i++){
PilihSubtema.options[i] = new Option(subtema[idtema][i].val,subtema[idtema][i].KodeMapel);
}
}
</script>
<body onload='loadtema()'>
<select id='PilihTema' name='PilihTema' class='form-control11'>
</select>
<select id='PilihSubtema' name='PilihSubtema' class='form-control11'>
</select>
<button input class="btn btn-success" id="submit" type="submit" name="add" value="Simpan" onclick="return(submitmapel());"/>
<i class="fa fa-save fa-fw"></i> Simpan
So far I see some errors in your code.
select.onchange = updateSubTema;
You are missing () for the function. Should be select.onchange = updateSubTema();
I'm not sure if var PilihTema = this; will actually select anything, personally i'd do it the following way.
loadTema function:
var select = document.getElementById("PilihTema");
select.onchange = updateSubTema(select.value);
updateTema function
function updateTema(pilihTema){
//Your code here
}
EDIT: If you mean you want to add an item per run through your for loop, I would suggest doing it the following way (I use jQuery as it is much easier in my opinion):
$(document).ready(function(){
<?php
echo "var tema = $jsonTema;";
echo "var subtema = $jsonSubTema;";
?>
//Load Tema
$.each(tema, function (i, item) {
//I am unsure as to what you mean by KodeMapel, though if this is associative arrays encoded as JSON, you will want to use item[val] and item[KodeMapel]
$("#PilihTema").append(new Option(item.val, item.KodeMapel));
});
//Called when the first select field is changed.
$("#PilihTema").change(function(){
//Get value of first select fields' selected item
var pilihValue = $("#PilihTema option:checked").val();
//Remove all the options from the second select field
$("#PilihSubtema").html("");
//For each subtema, with first select fields value, add option to second select field
$.each(subtema[pilihValue], function (i, item) {
//Again, I am unsure as to what you mean by KodeMapel, though if this is associative arrays encoded as JSON, you will want to use item[val] and item[KodeMapel]
$("#PilihSubtema").append(new Option(item.val, item.KodeMapel));
});
});
});

client side sorting using javascript

Ive been trying to build a web site that retrieves values from the database and then implements features such as sorting and filtering. I am building the query each time a filter is applied as of now, will definitely change to something more efficient. For the sorting, I want to implement it on the client side itself since the data is already present.
I went through a number posts from this forum and arrived at a piece of code that I included in mine. To give you a heads up on the web page, the sorting options are included as radio buttons. Whenever a user clicks on the "Apply" button, a javascript function is triggered which sorts the html table - which is populated using php.
Here is the code:
<script type="text/javascript">
function SortTable() {
var sortedOn = 1;
var table = document.getElementById('venue_list');
var tbody = table.getElementsByTagName('tbody')[0];
var rows = tbody.getElementsByTagName('tr');
var rowArray = new Array();
for (var i=0, length=rows.length; i<length; i++) {
rowArray[i] = new Object;
rowArray[i].oldIndex = i;
rowArray[i].value = rows[i].getElementsByTagName('td')[sortOn].firstChild.nodeValue;
}
//if (sortOn == sortedOn) { rowArray.reverse(); }
//else { sortedOn = sortOn; }
/*
Decide which function to use from the three:RowCompareNumbers,
RowCompareDollars or RowCompare (default).
For first column, I needed numeric comparison.
*/
if (sortedOn == 1) {
rowArray.sort(RowCompareStrings);
}
else {
rowArray.sort(RowCompare);
}
var newTbody = document.createElement('tbody');
for (var i=0, length=rowArray.length ; i<length; i++) {
newTbody.appendChild(rows[rowArray[i].oldIndex].cloneNode(true));
}
table.replaceChild(newTbody, tbody);
}
function RowCompare(a, b) {
var aVal = a.value;
var bVal = b.value;
return (aVal == bVal ? 0 : (aVal > bVal ? 1 : -1));
}
// Compare Strings
function RowCompareStrings(a, b) {
var index = b.localeCompare(a);
return index;
}
</script>
<div style="float: right;margin-right: -100px;" class="box2">
<h2>Sort by :</h2>
<input type="radio" id="s1" name="sort" value="1" />
<label for="f1"><?php echo 'Name'?></label>
<input type="radio" id="s1" name="sort" value="1" />
<label for="f1"><?php echo 'Location'?></label>
<br><br><br>
<div id="ContactForm" action="#">
<input name="sort_button" value="Apply" type = "button" id="sort_button" class="button" onclick="SortTable();"/>
</div>
</div>
<table>
<tbody>
while($row = mysqli_fetch_array($result))
{
$name = $row['NAME'];
$img = $row['IMAGE_SRC'];
$addr = $row['ADDRESS'];
$location = $row['LOCATION'];
echo "<script type='text/javascript'>map_function('{$addr}','{$name}','{$img}');</script>";
?>
<tr>
<td>
<a href="<?php echo $name?>">
<img src="<?php echo $img.".jpg"?>" height="100" width="100">
</a>
</td>
<td>
<a href="<?php echo $name?>">
<h3><?php echo $name?></h3>
</a>
<td>
</tr>
<?php
}
?>
</tbody>
</table>
For now, I'm fixing the sorting column number, sortedOn to 1 just to check if its working but to my dismay it is not. I have been trying to get it work since quite some time now. I am relatively new to Javascript and this is my first take on web development. Looking forward to a solution.
Thanks.
If what you want is to sort the rows of a table with javascript, you can implement sortable.js.
http://www.kryogenix.org/code/browser/sorttable/
I would recommend you that convert your query result to Json format using PHP json_encode(), this way you can deal with javascript all data in a more simple way.
Well I was able to figure out my mistake. There were multiple errors in the javascript function. Secondly the in the table was missing for the second column. In the javascript function, basically, I was comparing the rowArray objects themselves in the RowCompareStrings function. I should actually be comapring the rowArray.value with each other.

Dynamic Select Drop Box Generation Containing PHP Data

I need some help generating multiple select boxes. I am able to generate new boxes but they do not contain the SQL data that the boxes should have. I will link my javascript code first.
<script>
function add_file_field2(){
var container2=document.getElementById('file_container2');
var file_field2=document.createElement('select');
file_field2.name='animalCommony[]';
file_field2.type='animalCommony';
file_field2.value = 'animalCommony[]';
file_field2.text = 'animalCommony';
container2.appendChild(file_field2);
var br_field=document.createElement('br');
container2.appendChild(br_field);
}
function remove_field2() {
var container2=document.getElementById('file_container2');
lastChild = container2.lastChild;
if(lastChild !=0) {
container2.removeChild(lastChild);
file_field-= 1;
}
}
</script>
So I am not sure how I need to modify that code to generate the correct select boxes.
Here is my php code:
<?php
$db = get_db_connection('swcrc');
$db->connect();
$db->query("SELECT [ID], [Common_Name], [Scientific_Name] FROM dbo.All_Animals");
while($row = $db->fetch())
{
?>
<option value="<?php echo $row['Common_Name'];?> - <?php echo $row['Scientific_Name'];?>"><?php echo $row['Common_Name'];?> - <em><?php echo $row['Scientific_Name'];?></em></option>
<?php
}
?>
</select>
</div>
</p>
<p>
Add Another Animal
<br />
Remove Animal<br />
<br>
</p>
Finally I will have a screenshot of what it looks like after hitting the 'add another animal button' twice. Thank you for your help!
As you can see empty select boxes are generated.
Screen shot including an example of the kind of data that should populate the added boxes.
Screenshot of database
If all you want to do is copy the contents of the selection box, you don't need to query SQL again. Here's a javascript function that will do the copy, assuming your original selection box has id "myselect." I've also left you a jsfiddle below.
window.add_file_field2 = function () {
function copySelect(select) {
var newSelect = document.createElement('select');
newSelect.name = 'animalCommony[]';
newSelect.type = 'animalCommony';
newSelect.value = 'animalCommony[]';
newSelect.text = 'animalCommony';
for (var i = 0;i < select.options.length;i++) {
var option = document.createElement('option')
option.value = select.options[i].value
option.text = select.options[i].text
newSelect.appendChild(option)
}
return newSelect
}
var container2 = document.getElementById('file_container2');
container2.appendChild(copySelect(document.getElementById("myselect")));
var br_field = document.createElement('br');
container2.appendChild(br_field);
}
Here is a jsfiddle

Categories