<!DOCTYPE html>
<html>
<body onload="test();">
<script>
var number=1;
var input='<div><input type="text"><div>'+
'<div>'+number+'</div>'+
'<input type="text">';
function test(){
var div = document.getElementById('result');
div.innerHTML = div.innerHTML + input;
}
</script>
<div id="result"></div>
</body>
</html>
Can someone help me with code above? For some reason my first input box has size of 100 even should be 1.
You can't access JavaScript variables like number in php.
If you want to use number you need to do it in JavaScript like this:
<!DOCTYPE html>
<html>
<body onload="test();">
<script>
var number = 1;
var input = '<div><input type="text";';
input += number == 1 ? ' size="1" ' : ' size="100" ';
input += '><div>';
input += '<div>' + number + '</div>';
input += '<input type="text" ';
input += 1 == 1 ? ' size="1" ' : ' size="100" ';
input += '>';
function test() {
var div = document.getElementById('result');
div.innerHTML = div.innerHTML + input;
}
</script>
<div id="result"></div>
</body>
</html>
It is because php code is executed before js code. While php is executed it tries to check '+number+' is 1 which it is not. It is a string.
Php code is executed in server and js code in browser. That is huge difference.
Related
I want a user to be able to enter specific values into an input field and would like to be able to output the values WITH HTML "markup" such as '< div >' and '< p >' as text only. I have tried outputting it as a string as well but i cannot figure it out. Please help!
I would like it to operate like this:
Input value = x
Output = x
does it have to be output as a string so the browser doesnt only output = x? All insight helps!
Please See My Example Here:
<html>
<head>
<title>Markup Generator</title>
</head>
<body>
First name: <input id="first_name">
Last name: <input id="last_name">
<button id="say">Say hi!</button>
<hr>
<div id="result"></div>
<script>
function say_hi() {
var fname = document.getElementById('first_name').value;
var lname = document.getElementById('last_name').value;
var html = 'Hello <b>' + fname + '</b> ' + lname;
document.getElementById('result').innerHTML = html;
}
document.getElementById('say').addEventListener('click', say_hi);
</script>
<html>
<head>
<title>Markup Generator</title>
</head>
<body>
First name: <input id="first_name">
Last name: <input id="last_name">
<button id="say">Say hi!</button>
<hr>
<div id="result"></div>
<script>
function say_hi() {
var fname = document.getElementById('first_name').value;
var lname = document.getElementById('last_name').value;
var html = 'Hello <b>' + fname + '</b> ' + lname;
document.getElementById('result').innerText = html;
}
document.getElementById('say').addEventListener('click', say_hi);
</script>
You can use innerText instead of innerHTML
like this
document.getElementById('result').innerText = html;
I have a google sheet, maintaining a list of projects, with some scripting running behind it. I have been able to add functionality to click an Add Project button which opens an HTML window for entering the information, and on submit, add a new record to the sheet.
Now I am working on a process to remove a record if the status is changed to Cancelled. What I would like to do is show an html window listing certain details of the project, and give the user a chance to either go back without cancelling the project, or enter some notes as to why it's being cancelled and then continue.
Where I am stuck is populating the html window with the details of the project. I have figured out one way to do it, but I know that this isn't the best way.
Google Script:
function onEdit(e) {
if(e.range.getColumn() == 9 && e.value == "Cancelled" && e.source.getActiveSheet().getName() == "Summary") {
var cancelSheet = ss.getSheetByName(e.source.getActiveSheet().getName());
var cancelRange = cancelSheet.getRange(e.range.getRow(), 1, 1, cancelSheet.getLastColumn());
var cancelRow = cancelRange.getValues();
openCancelDialog(cancelRow);
}
}
function openCancelDialog(x) {
var html = HtmlService
//.createHtmlOutputFromFile('Cancel')
.createHtmlOutput(
'<table><tr><td colspan = \"2\"><b>You are cancelling the following project:</b></td></tr>' +
'<tr><td>Project Name: </td><td>' + x[0][4] + '</td></tr>' +
'<tr><td>Project Number: </td><td>' + x[0][0] + '</td></tr>' +
'<tr><td>Project Category: </td><td>' + x[0][1] + '</td></tr>' +
'<tr><td>Business Owner: </td><td>' + x[0][17] + '</td></tr>' +
'<tr><td>Project Manager: </td><td>' + x[0][18] + '</td></tr>' +
'</table>'
)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Cancel a Project');
}
This way is writing the html directly in the gs. What I'd like to do is have a separate html page that gets created. That can be done with this method (and is how I'm creating the Add Project dialog elsewhere in the gs):
function openCancelDialog(x) {
var html = HtmlService.createHtmlOutputFromFile('Cancel').setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Cancel a Project');
}
This would be Cancel.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
<!-- Scripting to get my values? -->
</script>
</head>
<body>
<!-- Layout the window
Add a Comments section
Add a button to go back without cancel
Add a button to submit the cancel and update -->
</body>
</html>
But what I haven't figured out is how to pass the array from the openCancelDialog function to the html, so it cab be shown on the page..
I suspect that I need to add scripting to the Cancel.html file to get those values. But is there a way to send that array to the html while it's being created?
Kos's answer gave me some ideas on how I could work it out. That, as well as some additional reading, especially https://www.w3schools.com/js/js_json_intro.asp and the follow up sections, helped me figure this one out.
New js code:
function onEdit(e) {
if(e.range.getColumn() == 9 && e.value == "Cancelled" && e.source.getActiveSheet().getName() == "Summary") {
var cancelSheet = ss.getSheetByName(e.source.getActiveSheet().getName());
var cancelRange = cancelSheet.getRange(e.range.getRow(), 1, 1, cancelSheet.getLastColumn());
var cancelRow = cancelRange.getValues();
//openCancelDialog(cancelRow);
var aSheet = e.source.getActiveSheet().getName();
var column = e.range.getColumn();
var row = e.range.getRow();
Logger.log("Col: " + column + " Row: " + row + " Sheet: " + aSheet);
Logger.log(cancelRow);
}
Logger.log(e);
}
function openCancelDialog(row) {
var ui = SpreadsheetApp.getUi();
// get template
var template = HtmlService.createTemplateFromFile('Cancel');
var myJSON = JSON.stringify(row);
// pass data to template
template.data = myJSON;
// get output html
var html = template.evaluate();
// show modal window
ui.showModalDialog(html, 'Cancel a Project');
}
New HTML:
<!DOCTYPE html>
<html>
<body>
<table>
<tr><td>Number: </td><td id="number"></td></tr>
<tr><td>Name: </td><td id="name"></td></tr>
<tr><td>Category: </td><td id="category"></td></tr>
<tr><td>Business Owner: </td><td id="owner"></td></tr>
<tr><td>Project : </td><td id="manager"></td></tr>
</table>
<script>
var objII = JSON.parse(<?=data?>);
document.getElementById("number").innerHTML = objII[0][0];
document.getElementById("name").innerHTML = objII[0][4];
document.getElementById("category").innerHTML = objII[0][1];
document.getElementById("owner").innerHTML = objII[0][17];
document.getElementById("manager").innerHTML = objII[0][18];
</script>
</body>
</html>
I suspect there may be more elegant ways to do this, and probably even more "correct" ways. But this seems to be working for what I needed it to do, so I figured I'd post it in case someone else was looking.
Thank you
Use HtmlService.createTemplateFromFile:
function openCancelDialog(row)
{
var ui = SpreadsheetApp.getUi();
// get template
var template = HtmlService.createTemplateFromFile('Cancel');
// pass data to template
template.data = {
row: JSON.stringify(row)
};
// get output html
var html = template.evaluate();
// show modal window
ui.showModalDialog(html, 'Cancel a Project');
}
Cancel.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var row = <?!=data.row?>;
//document.write(row);
</script>
</body>
</html>
Detailed template documentation: https://developers.google.com/apps-script/guides/html/templates
Here's another way to do it. I like to do it this way because I have a lot more control than I do with templates.
This is a script that I did when I was working on an email example script that is contained in a spreadsheet. This script is a little less complicated because it's just for giving the user the option for removing sent emails from the emailsetup page and archiving them on another page. It does it by creating html on the fly and collecting it as a string and then adding it to another page of html. I launch the html at the end of the script as a dialog that allows the users to select which emails to archive by checking checkboxes and clicking on a button called Archive Selected. I found it easier to put my javascript functions together in a standard html file and then run that through HtmlService first and append the string later.
Here's the script:
function archiveSelectedEmails()
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('EmailSetup');
var rng=sht.getDataRange();
var rngA=rng.getValues();
var s='<html><head><script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script></head><body>';
var s='';
for(var i=2;i<rngA.length;i++)
{
var dataA={};
for(var j=0;j<rngA[1].length;j++)
{
dataA[rngA[1][j]]=rngA[i][j];
}
var row=Number(i+1);
s+='<div id="row' + row + '"><input type="checkbox" name="email" value="' + Number(i+1) + '" />' + ' <strong>Row:</strong> ' + Number(i+1) + ' <strong>Name:</strong> ' + dataA.Name + ' <strong>Email:</strong> ' + dataA.Email + ' <strong>Subject:</strong> ' + dataA.Subject + ' <strong>DateSent:</strong> ' + Utilities.formatDate(new Date(dataA.DateSent), 'GMT-6', "M/dd/yyyy HH:mm:ss") + '</div>';
}
s+='<br /><input type="button" value="Exit" onClick="google.script.host.close();" /><input type="button" value="Archive Checked" onClick="getCheckedBoxes(\'email\');" />';
var html=HtmlService.createHtmlOutputFromFile('htmlToBody').setWidth(800).setHeight(250);
html.append(s);
SpreadsheetApp.getUi().showModelessDialog(html, 'Select Emails to Archive');
}
Here's the html file 'htmlToBody':
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var rowsToArchive = [];
for (var i=0; i<checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
rowsToArchive.push(Number(checkboxes[i].value));
}
}
google.script.run
.withSuccessHandler(setResponse)
.archiveSelectedRows(rowsToArchive);
}
function setResponse(a)
{
var s='<br />Rows: ';
for(var i=0;i<a.length;i++)
{
if(i>0)
{
s+=', ';
}
s+=a[i];
var id='#row' + a[i]
$(id).css('display','none');
}
s+='<br />Total: ' + a.length;
google.script.run.displayMessage(s,'Archived Rows')
}
console.log('script here');
</script>
</head>
<body>
I took your project idea and ran with it a little.
These are the google scripts. You'll notice I started with the name of your function.
function openCancelDialog1()
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('Projects');
var rng=sht.getDataRange();
var rngA=rng.getValues();
var s='';
for(var i=1;i<rngA.length;i++)
{
var dataA={};
for(var j=0;j<rngA[0].length;j++)
{
dataA[rngA[0][j]]=rngA[i][j];
}
var row=Number(i+1);
s+='<div id="row' + row + '"><input type="checkbox" name="project" value="' + row + '" />' + ' <strong>Row:</strong> ' + Number(i+1) + ' <strong>Name:</strong> ' + dataA.Name + ' <strong>Project:</strong> ' + dataA.Description + '</div>';
}
s+='<br /><input type="button" value="Exit" onClick="google.script.host.close();" /><input type="button" value="Cancel and Archive Checked" onClick="getCheckedBoxes(\'project\');" />';
var html=HtmlService.createHtmlOutputFromFile('htmlToBody').setWidth(800).setHeight(250);
html.append(s);
SpreadsheetApp.getUi().showModelessDialog(html, 'Select Project to Cancel');
}
function archiveSelectedRows(rows)
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('Projects');
var dest=ss.getSheetByName('ArchivedProjects');
var rng=sht.getDataRange();
var rngA=rng.getValues();
var deleted=[];
for(var i=rngA.length-1;i>1;i--)
{
if(rows.indexOf(i+1)>-1)
{
deleted.push(Number(i+1));
rngA[i][4]=Utilities.formatDate(new Date(), 'GMT-7', 'M/d/yyyy')
dest.appendRow(rngA[i]);
sht.deleteRow(i+1);
}
}
var msg='Row Numbers Deleted = ' + deleted;
var title='Rows Deleted';
var timeout=10;
return deleted;
}
function displayMessage(msg,title)
{
msg+='<br /><input type="button" value="Exit" onClick="google.script.host.close()"; />';
var html=HtmlService.createHtmlOutput(msg).setWidth(400).setHeight(300);
SpreadsheetApp.getUi().showModelessDialog(html, title);
}
This is the htmlTobody file. It's been modified a bit for this situation.
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var rowsToArchive = [];
for (var i=0; i<checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
rowsToArchive.push(Number(checkboxes[i].value));
}
}
google.script.run
.withSuccessHandler(setResponse)
.archiveSelectedRows(rowsToArchive);
}
function setResponse(a)
{
var s='<br />Row Numberss: ';
for(var i=0;i<a.length;i++)
{
if(i>0)
{
s+=', ';
}
s+=a[i];
var id='#row' + a[i]
$(id).css('display','none');
}
s+='<br />Total: ' + a.length;
google.script.run.displayMessage(s,'Canceled Rows')
}
console.log('script here');
</script>
</head>
<body>
And this is what my 'Projects' tab looks like. And I have a Projects tab and an ArchivedProjects tab. When I archive the projects they get copied into the ArchivedProjects sheet.
I'm kinda new to html/javascript. I wanted to store the user input value in array (already done this part) and display it into HTML table(I'm stuck at this one). When user press the button, the table will show up at the bottom.
Here's my code so far:
HTML
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<form>
<h1>Please enter data</h1>
<input id="title" type="text" placeholder="Title" />
<input id="name" type="text" placeholder="Name" />
<input id="tickets" type="text" placeholder="Tickets" />
<input type="button" value="Save/Show" onclick="insert()" />
</form>
<div id="display"></div>
</body>
</html>
This is my Javascript code:
var titles = [];
var names = [];
var tickets = [];
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
var messageBox = document.getElementById("display");
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
function clearAndShow () {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "<tr>Titles</tr>" + titles.join(" ") + "<td></td>";
messageBox.innerHTML += "<tr>Name</tr> <td>" + names.join(" ") + "</td>";
messageBox.innerHTML += "<tr>tickets</tr> <td>" + tickets.join(" ")+ "</td>";
}
I can't display the array into the tables. I'm quite new to Javascript/HTML so any help would be appreciated. :D
As I have already commented, you will have to loop over array and compute html and set it. Your function clearAndShow will set last value only.
I have taken liberty to update your code. You should not save data in different arrays. Its better to use one array with proper constructed object.
JSFiddle
var data = [];
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
var messageBox = document.getElementById("display");
function insert() {
var title, name, ticket;
title = titleInput.value;
name = nameInput.value;
ticket = ticketInput.value;
data.push({
title: title,
name: name,
ticket: ticket
});
clearAndShow();
}
function clearAndShow() {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = computeHTML();
}
function computeHTML() {
var html = "<table>";
console.log(data)
data.forEach(function(item) {
html += "<tr>";
html += "<td>" + item.title + "</td>"
html += "<td>" + item.name + "</td>"
html += "<td>" + item.ticket + "</td>"
html += "</tr>";
});
html += "</table>"
return html;
}
article,
aside,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<head>
<script class="jsbin" src=""></script>
<script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<body>
<form>
<h1>Please enter data</h1>
<input id="title" type="text" placeholder="Title" />
<input id="name" type="text" placeholder="Name" />
<input id="tickets" type="text" placeholder="Tickets" />
<input type="button" value="Save/Show" onclick="insert()" />
</form>
<div id="display"></div>
</body>
Please try and change your js code like below, not the most elegant but a start:
function clearAndShow () {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "<tr>";
messageBox.innerHTML += "<td>Titles</td>";
messageBox.innerHTML += "<td>Name</td>";
messageBox.innerHTML += "<td>Tickets</td>";
messageBox.innerHTML += "</tr>";
for(i = 0; i <= titles.length - 1; i++)
{
messageBox.innerHTML += "<tr>";
messageBox.innerHTML += "<td>" + titles[i]+ "</td>";
messageBox.innerHTML += "<td>" + names[i] + "</td>";
messageBox.innerHTML += "<td>" + tickets[i]+ "</td>";
messageBox.innerHTML += "</tr>";
}
}
and your display html like so:
<table id="display"></table>
have a look at fiddle over here https://jsfiddle.net/gvanderberg/cwmzyjf4/
The data array in Rajesh's example is the better option to go for.
you deleted your last question about the numbering of authors, but I wrote a big answer to you for it. Just for you to have it :
Wow, man you have several problems in your logic.
First, you have to specify to your form not to submit when you click on one or the other submit buttons (Add a book, or Display book) :
<form onsubmit="return false;">
Second, you have to define your numbering var to 0 and use it when you want to assign a number to a book :
var numbering = 0;
Then, in your addBook function, you have to use that global numbering variable to set you no variable :
function addBook() {
numbering++; // increments the number for the books (1, 2, 3, etc)
var no, book, author;
book = bookInput.value;
author = nameInput.value;
no = numbering;
...
}
Then you have all kind of mistakes like double ";" on certain lines etc.
A huge mistake is also done on your code when you use "forEach". Notice this function only works when you use jQuery library ! You have to include it before you use it :
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
An other huge mistake you do is that your "Display" button has the id "display" and your messageBox also has this id. This is forbidden because when you want to use the element which has this ID, Javascript won't know which of the two is the good one. So rename your button id in displayAuthors :
<input type="submit" id="displayAuthors" value="Display" onclick="displayBook()" />
Now, what you also can do, is to call your displayBooks function everytime you add a new book like this :
function addBook() {
numbering++;
var no, book, author;
book = bookInput.value;
author = nameInput.value;
no = numbering;
data.push({
book: book,
author: author,
no: no
});
displayBook();
}
So I did all these things here on CodePen : https://codepen.io/liorchamla/pen/JMpoxM
The JQuery solution
Here you used the basics of Javascript (called Vanilla JS) which is very cool because you have to learn it, but I also wrote you a CodePen to show you how you could have done this with jQuery :-)
Here it is : http://codepen.io/liorchamla/pen/oxwNwd
Basicly, the javascript changed to this :
$(document).ready(function(){
var data = []; // data is an empty array
// binding the addBook button with the action :
$('#addBook').on('click', function(){
var book = {
title: $('#bookname').val(),
author: $('#authors').val(),
// note we won't use a numbering variable
};
data.push(book);
// let's automaticly trigger the display button ?
$('#displayBooks').trigger('click');
});
// binding the displayBooks button with the action :
$('#displayBooks').on('click', function(){
$('#display').html(computeHTML());
});
function computeHTML(){
// creating the table
html = "<table><tr><th>No</th><th>Book</th><th>Author</th></tr>";
// for each book in the data array, we take the element (book) and the index (number)
data.forEach(function(element, index){
// building the table row, note that index starts at 0, so we increment it to have a start at 1 if it is 0, 2 if it is 1 etc.
html += "<tr><td>" + parseInt(index++) + "</td><td>" + element.title + "</td><td>" + element.author + "</td></tr>";
})
html += "</table>";
// returning the table
return html;
}
})
You might find it complicated, but with time you will see that jQuery helps a lot !
They are lot of things we could enpower in this script but this is a good starting, don't you think ?
Cheers from Marseille, France !
In the following code I am not able to set a value which has double quotes.
<html>
<head>
</head>
<body>
<div id="d"/>
<button id="button">Click Me</button>
</body>
<script>
var button = document.getElementById("button");
button.onclick = function() {
var d = document.getElementById("d");
var value = 'some"val\'ue';
var h = "<input type=\"text\" id=\"someid\" value=\"" + value + "\">"
d.innerHTML = h;
}
</script>
</html>
Is there any way to do it?
Note: Due to some reasons I cant render the input element first and later set the value using .value. I have to do it using innerHTML.
" is html way of saying ".
<script type="text/javascript">
function Msg1(){
var a="noida";
id=1;
document.getElementById('myText').innerHTML = '<p onclick="nice(id)">'+a+'</p>';
}
function Msg2(){
document.getElementById('myText').innerHTML = 'Try message 1 again...';
}
</script>
<input type="button" onclick="Msg1()" value="Show Message 1" />
<input type="button" onclick="Msg2()" value="Show Message 2" />
<p id="myText"></p>
when i click on Show Message 1 it send id as a charecter not 1 i want to it send me 1
Thanks
You could do something like:
'<p onclick="nice(\"' + id + '\")">'+a+'</p>';
Or:
'<p onclick="nice(' + escape(JSON.stringify(id)) + ')">'+a+'</p>';
But this gets very unreadable very quickly.
Using this method you can't send things that aren't easily serializable. A more robust, and involved, solution would use the DOM API and EventListener API.
Example:
var id = { foo: "bar" };
var p = document.createElement("p");
p.addEventListener("click", function () {
nice(id);
});
p.innerText = "ipsum lorem";
document.body.appendChild(p);
You already have concatenation right near where you need it:
'<p onclick="nice('+id+')">'+a+'</p>';
make your innerHTML as
'<p onclick="nice(\"' + id + '\")">'+a+'</p>'
Replace your Msg1() Javascript function as below
function Msg1(){
var a="noida";
var id = 1;
document.getElementById('myText').innerHTML = '<p onclick="nice(\"' + id + '\")">'+a+'</p>';
}