Reinvestigating "Trying to make different HTML paragraph show depending on selection" - javascript

I asked about this previously but failed to provide enough detail so I thought I'd give credit where it's due (the responses were excellent, but didn't answer my issue because I'd failed to provide enough information) and start over.
So I have this pair of modals; one that accepts a text input, and one that gets input out of a dropdown selection, in google sheets and scripts (see hyperlinks) that is supposed to provide a different descriptive paragraph depending on which which selection the user has made from a dropdown step. Currently it just shows a single paragraph that doesn't change depending on selection. I want it to:
show id='PUBLIC' paragraph when Public is selected, show id='INTERNAL' when internal is selected. Etc. Etc.
Save their selection and send it to be pasted it where it's needed.
function AddValuesFromModal(selectValue) {
var documentId = SpreadsheetApp.getActiveSpreadsheet().getId();
console.log("Getting document log...");
var infoSheet = SpreadsheetApp.getActive().getSheetByName('Information Control')
console.log("Got document!");
console.log("Selected value: " + selectValue);
console.log("Start setting value....");
infoSheet.getRange('C4').setValue(selectValue);
console.log("Value has been set!");
}
function myFunk() {
// Display a dialog box for each field you need information for.
var documentProperties = PropertiesService.getDocumentProperties();
var ui = SpreadsheetApp.getUi();
//var response = ui.prompt('Enter Name', 'Enter owners person's name', ui.ButtonSet.OK);
var nameResponse = ui.prompt("Enter the name of the document OWNER");
var salesperson = nameResponse.getResponseText();
var documentProperties = PropertiesService.getDocumentProperties();
var infoSheet = SpreadsheetApp.getActive().getSheetByName('Information Control')
var date = new Date();
var htmlDlg = HtmlService.createHtmlOutputFromFile("HTML_myHtml")
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
var modal = SpreadsheetApp.getUi();
modal.showModalDialog(htmlDlg, "Document Classification");
//Get Current Document ID
var documentId = SpreadsheetApp.getActiveSpreadsheet().getId();
console.log(documentId);
//Get the document body as a variable
var body = SpreadsheetApp.openById(documentId).getDataRange().getValues();
console.log(body);
//Insert the entries into the document
infoSheet.getRange('C5').setValue(salesperson);
infoSheet.getRange('C8').setValue(date);
}
<form id="docType">
<select id="selectDocumentType" name="documentClass" onchange='CheckSelect(this.value);'>
<option value="PUBLIC">Public</option>
<option value="INTERNAL">Internal</option>
<option value="CONFIDENTIAL">Confidential</option>
<option value="SECRET">Secret</option>
</select>
<body>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:block;" class="light work"
id="Choose" >Please Choose any one</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="PUBLIC" >Wizard Is working</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="INTERNAL" >Wizard Is Twerking</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="CONFIDENTIAL" >Wizard Is Laughing</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="SECRET" >Wizard Is Eating</p>
</body>
<hr/>
<input type="button" onClick="formSubmit();" value="Submit" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
function HideAll(val)
{
var all = document.getElementsByClassName(val);
for(var i =0; i<all.length; i++)
all[i].style.display = 'none';
}
function CheckSelect(val){
HideAll('work');
document.getElementById(val).style.display='block';
}
function formSubmit(){
Submit();
}
function Submit() {
var selectedValue = $('#selectDocumentType').val();
console.log(selectedValue);
google.script.run
.withSuccessHandler(closeIt)
.AddValuesFromModal(selectedValue);
};
function closeIt(){
google.script.host.close();
};
</script>

I updated the script. "CheckColors" should have been "CheckSelect". Bad version control facepalm.

Related

How do I get cell values on click event from webpage tabs after the first one?

I have tried javascript and JQuery. I know how to write the code to get the cell values from my first tab but the same function does not work on the other tabs on my webpage. It seems as if the table in my other tabs is just a view. I am new to javascript and JQuery so think I might be missing something easy. I have used ".on" in my click function and that doesn't help. Here is the Javascript code and JQuery code, both work by grabbing the cell value I click but only for the first tab:
JavaScript
init();
function init(){
addRowHandlers('customerTable');
}
function addRowHandlers(tableId) {
if(document.getElementById(tableId)!=null){
var table = document.getElementById(tableId);
var rows = table.getElementsByTagName('tr');
var cid = '';
var name = '';
for ( var i = 1; i < rows.length; i++) {
rows[i].i = i;
rows[i].onclick = function() {
cid = table.rows[this.i].cells[0].innerHTML;
name = table.rows[this.i].cells[1].innerHTML;
alert('cid: '+cid+' name: '+name);
};
}
}
}
JQuery
$('#customerTable').find('tr').click(function() {
var $id = $(this).closest("tr")
.find(".custId")
.text();
var $name = $(this).closest("tr")
.find(".custName")
.text();
alert($name);
$('.defaultTextBox.text_custId:text').val($id);
$('.defaultTextBox.text_custName:text').val($name);
});
In the end my goal is to get the elements clicked and set the text in my text boxes to those values, which you can see I did in the JQuery, but it only works on my first page. I need the click in my table to work on all tabs. Thanks in advance!
Edit
<div id="removeCustomer" class="tabcontent">
<h3>Pick a customer to remove!</h3>
<div class="container">
<br />
<h2 align="center">Search here to find the customer you want to remove</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by name, phone number, email, or state" class="form-control" />
</div>
</div>
<br />
<div class="result"></div>
</div>
</div>
The "removeCustomer" id is one of the tabs. So I have multiple tabs using the same, "result", which I think is the problem I just do not know how to solve it. If I Left out "result" it would not generate a table.
Here is the JQuery which uses a php file to connect to my database and get my data. And this is what generates result.
JQuery
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetchCustomers.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('div.result').html(data);
}
});
}
$('input.form-control').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
Thanks again.

How to use multiple arguments in Google App Script function and check what radio box is checked across HTMLService?

HTML Page:
<html>
<body>
<div id="addGamePrompt">
<form>
First Pick Team:
<div id="containerT1"><input type="text" id="team1" name="team1"> My Team <input type="radio" name="myTeam" value="team1" id="checkTeam1" checked></div>
<br><br>
Second Pick Team:
<div id="containerT2"><input type="text"id="team2" name="team2"> My Team <input type="radio" name="myTeam" value="team2" id="checkTeam2">
<br></div>
</form>
</div>
<input id="submitBut" type="button" onClick="formSubmit()" value="Ok"/>
<script type="text/javascript">
function formSubmit() {
google.script.run.getTeams(document.forms[0], 1);
}
</script>
</body>
</html>
Google App Script
function myFunction() {
// Display a modal dialog box with custom HtmlService content.
var htmlOutput = HtmlService
.createHtmlOutputFromFile('addGamePrompt.html')
.setWidth(300)
.setHeight(130);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Enter Teams');
}
function getTeams(form,flag1){
var arg1 = arguments[0]; //form argument value
var arg2 = arguments[1]; //flag1 argument value
var ss = SpreadsheetApp.getActiveSpreadsheet();
var team1 = arg1.team1; //gets value of form in HTML page
var team2 = arg1.team2; //see above
var flagCheck = arg2; //sets flagCheck as whatever argument flag1 is
ss.toast(team1); //prints out in box the value of team1
}
I want to be able to pass the value of the text boxes, and check which radio box is checked through the google app script (if the first one is flag1=1 if the second one is flag1 =2), but nothing is happening.
NOTE: Using this in Google Sheets.
I would change the names for the radio buttons to:
name="myTeam1"
name="myTeam2"
You don't need to send the second parameter, just use:
google.script.run.getTeams(document.forms[0]);
Your server side code should be changed to:
function getTeams(form){
//To see what is printed to the Log, use the View menu, and Logs
Logger.log('team1: ' + form.team1);
Logger.log('myTeam1: ' + form.myTeam1);
Logger.log('team2: ' + form.team2);
Logger.log('myTeam2: ' + form.myTeam2);
var team1 = form.team1; //gets value of form in HTML page
var team2 = form.team2; //see above
var myTeam1 = form.myTeam1;//Get value of radio button
var myTeam2 = form.myTeam2;
//Whichever radio button is NOT checked will have a value of undefined
var flagCheck = myTeam1?team1:team2; //sets flagCheck as whatever radio button is checked
Logger.log('flagCheck: ' + flagCheck);
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.toast(team1); //prints out in box the value of team1
}
If a form element is passed with google.script.run.getTeams(formElement); then it must be the only parameter. You can't have two, or more parameters if you are passing a form element. So, I would create a new object, put the form answers into the object, put any other data or answers into the new object, and pass the object to the GS server function.
var dataObject = {};
dataObject.value1 = answerOne;
dataObject.value2 = answerTwo;
dataObject.value3 = answerThree;
google.script.run.getTeams(dataObject);

Updating listbox selected index

I have a google script which reads and writes between a google spreadsheet and a google form. It's basically a form to access a materials database.
When first accessing the form, it shows all the fields blank, a populated 'selector' listbox of material id's (CW_ID) and an option for "New" part in the selector listbox. If user stays on "New", the fields stay blank for user to populate them manually and appends it as a new item in the database. If user scrolls through the 'selector' listbox and selects a CW_ID, it will pull from the spreadsheet and populate the fields with data corresponding to the selected CW_ID, for the user to then edit (modify a detail about a part).
Because I am using a SQL structure for my database, I have a couple linked tables:
materials table (which holds most information about the part, including an ID for manufacturer [manufacturer_ID])
manufacturers table (which is linked to the materials.manufacturer_ID)
Right now, the form only uses the materials sheet to populate the fields, so in the field for 'manufacturer', it only shows the ID number. For user purposes, I want the script to check the manufacturer_ID shown in the materials sheet, go into manufacturers sheet, find a match and have the manufacturers listbox show it as the currently selected index. (Or just have the name of the manufacturer show up in the field)
This is part of my script so far:
(Scroll to bottom for "//****THIS IS THE PART I'M WORKING ON")
function doGet() {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/something")
var materialsSheet = ss.getSheetByName('materials');
var manufacturersSheet = ss.getSheetByName('manufacturers');
var vendorsSheet = ss.getSheetByName('vendors');
var usersSheet = ss.getSheetByName('users');
var projectApp = UiApp.createApplication();
projectApp.setTitle("Materials Form");
var activeEmail = Session.getActiveUser().getEmail();
//I create the vertical panel.
var panel = projectApp.createVerticalPanel().setId('face');
//Here is where I actually create the drop down menu, and assign the function "goSelection" to be activated whenever a selection is made.
var selector = projectApp.createListBox(true);
selector.setName('selectionBox').setId('selectionBox').addItem('New');
var materialsData = materialsSheet.getDataRange().getValues();
//do until row is less than length of
for (var i=0; i < materialsData.length; i++){
if (materialsData [i][1] == "Email"){
//if row in Column B does not equal gmail, skip to i++
continue;
}
//add Column C (CW_ID) of current row to the selector list
selector.addItem(materialsData [i][2]);
}
selector.setSelectedIndex(0);
var selectHandler = projectApp.createServerHandler('goSelection');
selectHandler.addCallbackElement(panel);
selector.addChangeHandler(selectHandler);
//Here is where I create the drop down menu to show list of manufacturers from manufacturers sheet
var manufSelectorLabel = projectApp.createHTML("<br><b>Manufacturer</b><br>").setWidth('100%');
var manufSelector = projectApp.createListBox(true);
manufSelector.setName('manufSelectionBox').setId('manufSelectionBox').addItem('New');
var manufacturersData = manufacturersSheet.getDataRange().getValues();
//do until row is less than length of
for (var i=0; i < manufacturersData.length; i++){
if (manufacturersData [i][1] == "Email"){
//if row in Column B does not equal gmail, skip to i++
continue;
}
//add Column C (Manufacturers) of current row to the selector list
manufSelector.addItem(manufacturersData [i][3]);
}
manufSelector.setSelectedIndex(0);
var manufSelected = manufSelector.SelectedItem;'
//**I am unsure whether this should have it's own function
//var manufSelectHandler = projectApp.createServerChangeHandler('goManuf');
//manufSelectHandler.addCallbackElement(panel);
//manufSelector.addChangeHandler(manufSelectHandler);
var gmailLabel = projectApp.createHTML("<br><b>Gmail:</b><br>").setWidth('100%');
var gmailField = projectApp.createTextArea().setSize('100%', '25px');
gmailField.setName('gmailArea').setId('gmailArea');
gmailField.setText(activeEmail);
var savedLabel = projectApp.createLabel('Thank you for your submission.');
savedLabel.setVisible(false).setId('sLabel');
//At this point, I'm actually declaring the variables for all the fields and text for the actual form.
var selectorLabel = projectApp.createHTML("<br><b>Select CW_ID from list.</b>").setId('selectLabel');
var descriptionLabel = projectApp.createHTML("<br><b>Description</b><br>").setWidth('100%');
var descriptionField = projectApp.createTextArea().setSize('100%', '100px');
descriptionField.setName('descriptionArea').setId('descriptionArea');
var manufacturerLabel = projectApp.createHTML("<br><b>Manufacturer</b></br>").setWidth('100%');
var manufacturerField = projectApp.createTextArea().setSize('100%x', '25px');
manufacturerField.setName('manufacturerArea').setId('manufacturerArea');
var manufacturerListLabel = projectApp.createHTML("<br><b>ManufacturerList</b></br>").setWidth('100%');
var manufacturerListField = projectApp.createTextArea().setSize('100%x', '25px');
manufacturerListField.setName('manufacturerListArea').setId('manufacturerListArea');
var modelnumberLabel = projectApp.createHTML("<br><b>Model Number</b><br>").setWidth('100%');
var modelnumberField = projectApp.createTextArea().setSize('100%', '25px');
modelnumberField.setName('modelnumberArea').setId('modelnumberArea');
//Next, i create the save button and assign the function "saved" to be activated whenever the button is pressed.
var saveButton = projectApp.createButton('Save');
var saveHandler = projectApp.createServerHandler('saved');
saveHandler.addCallbackElement(panel);
saveButton.addClickHandler(saveHandler);
//Now that all the componentes of the form have been declared and set up, I'm going to assemble them on the panel.
panel.setSpacing(6);
panel.add(nameLabel);
panel.add(nameField);
panel.add(gmailLabel);
panel.add(gmailField);
panel.add(selectorLabel);
panel.add(selector);
panel.add(descriptionLabel);
panel.add(descriptionField);
panel.add(manufSelectorLabel);
panel.add(manufSelector);
panel.add(manufacturerLabel);
panel.add(manufacturerField);
panel.add(modelnumberLabel);
panel.add(modelnumberField);
panel.add(saveButton);
panel.add(savedLabel);
projectApp.add(panel);
return projectApp;
}
//This function looks to see what has been selected in the drop down menu, and then pulls the appropriate data from the spreadsheet to display in the fields.
function goSelection(e){
var activeEmail = Session.getActiveUser().getEmail();
var app = UiApp.getActiveApplication();
var gmailField = app.getElementById('gmailArea');
var nameField = app.getElementById('nameArea');
var chosen = e.parameter.selectionBox;
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/something")
var materialsSheet = ss.getSheetByName('materials');
var manufacturersSheet = ss.getSheetByName('manufacturers');
var vendorsSheet = ss.getSheetByName('vendors');
var materialsData = materialsSheet.getDataRange().getValues();
var manufacturersData = manufacturersSheet.getDataRange().getValues();
var vendorsData = vendorsSheet.getDataRange().getValues();
var panel = app.getElementById('face');
var standardpartField = app.getElementById('standardpartArea');
var descriptionField = app.getElementById('descriptionArea');
var manufacturerField = app.getElementById('manufacturerArea');
var manufacturerListField = app.getElementById('manufSelectionBox');
var modelnumberField = app.getElementById('modelnumberArea');
if (chosen != 'New') {
for (var i=1; i < materialsData.length; i++){
if (materialsData [i][1] == "Email"){
//if row in Column B does not equal gmail, skip to i++
continue;
}
if (materialsData [i][2] != chosen){
continue;
}
nameField.setText(materialsData [i][0]);
gmailField.setText(materialsData [i][1]);
standardpartField.setText(materialsData [i][3]);
descriptionField.setText(materialsData [i][4]);
//****THIS IS THE PART I'M WORKING ON
//set manufacturerField to manufacturer of current row
//loop through manufacturer sheet until row matches with manufacturersField
//when a match is found, selector box index to same row
manufacturerField.setText(materialsData [i][5]);
for (var i=1; i < manufacturersData.length; i++){
if (manufacturersData [i][1] == "Email"){
//if row in Column B does not equal Email, skip to i++
continue;
}
if (manufacturersData [i][2] != manufacturerField){
continue;
}
manufacturerListField.setSelectedIndex(i);
}
modelnumberField.setText(materialsData [i][6]);
}
}
This makes sense to me, but it doesn't work. I click on a part in the selector listbox, and all the info populates into the fields, as I want it to. However, the manufacturer listbox does not jump to the proper manufacturer (as populated in the manufacturer field), it just sits there and stays as is.
(See image to get an idea of what the form looks like)
http://oi61.tinypic.com/6h6tqp.jpg
Manufacturer listbox and field show up, but right now, only the manufacturer field changes to show the data when a part is selected)
Any help would be GREATLY appreciated! :)
Here is some HTML that can get you started with the HTML Service:
Input Form HTML
<div>
<div>
Name:
<select>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
</select>
</div>
<br/>
<div>
Gmail:
<select>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
</select>
</div>
<br/>
<div>Select_CW_ID_From List:</div>
<select name="CW_ID" multiple>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
</select>
</div>
<br/>
<div>Standard Part</div>
<input type="text"/>
<br/>
<br/>
<div>Description</div>
<textarea rows="4" cols="50" name="comment" form="usrform">
Enter text here...</textarea>
</div>
<script>
function onSuccess(argReturnValue) {
alert('was successful ' + argReturnValue);
}
google.script.run.withSuccessHandler(onSuccess)
.nameOfFunctionInGS_File();
</script>
Download Notepad++: Notepad plus plus
And design your HTML in that. Then create an HTML file in your Apps Script project.
Your doGet() should just have the code that serves the HTML.
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('myHTML_File_Name_Here')
.evaluate() // evaluate MUST come before setting the NATIVE mode
.setTitle('Materials Form')
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
};
Create another .gs file for dealing with the data. That's where all your code for writing data to the spreadsheet will go.
If you need to populate select boxes, you can do that with JavaScript in a script tag of the HTML.
With what I've given you, you should be able to create a Stand Alone Apps Script HTML Service app. Publish it, and run it. You probably did that with your current project.

Is there a way to use document.write() and not overlap everything?

I have this HTML/Javascript code and I want to be able to print the product of a function inside the body of my code. Here is my code:
<form>
<div class="answer1wrap">
<label>Select your top champion:</label>
<select id="topSelect">
<option value="void">Select a champion</option>
<option value="aatrox">Aatrox</option>
<option value="ahri">Ahri</option>
<option value="akali">Akali</option>
</select>
</div>
</form>
<button class="btn btn-default" id="checkbtn" onclick="topAnswer();" type="button"><span class="glyphicon glyphicon-check"></span> Calculate Win Chance</button>
The JavaScript I have is this:
< script >
function topAnswer() {
var element = document.getElementById("topSelect");
var elementValue = element.value;
if (elementValue == "aatrox") {
document.write("You selected Aatrox for your teams top lane champion");
}
}
< /script>
If you select "Aatrox" it executes the document.write and prints what I want it to. But I don't want to to overwrite everything. What do I use to make my message appear after the "The top champion you selected is" line.
Here is a jsbin of the console: http://jsbin.com/eSiveyU/2/
Thanks
You have to create an additional DOM element and put the result value there. Quick example: http://jsbin.com/OkERuQeJ/1
document.getElementById("selectionResult").innerHTML = elementValue;
This might help you. http://jsfiddle.net/KPz6X/embedded/result/
I have created a div which will display your result below your button. No need to use document.write(). You can simple use the text() method of jQuery to modify the text of the div.
HTML
<form>
<div class="answer1wrap">
<label>Select your top champion:</label>
<select id="topSelect">
<option value="void">Select a champion</option>
<option value="aatrox">Aatrox</option>
<option value="ahri">Ahri</option>
<option value="akali">Akali</option>
</select>
</div>
</form>
<button class="btn btn-default" id="checkbtn" type="button"><span class="glyphicon glyphicon-check"></span> Calculate Win Chance</button>
<div class="display">
<p>The top champion you selected is: </p>
</div>
jQuery
$(document).ready(function(){
$(".btn-default").on('click', function () {
if ($("#topSelect").val() == "aatrox") {
$(".display p").text("You selected Aatrox for your teams top lane champion.");
}
});
});
You can store the message 'The top champion you selected is:' in variable once and concate it with selected option and display it in result box. The code would be for this.
function topAnswer(){
var element = document.getElementById("topSelect");
var elementValue = element.value;
if(elementValue == "aatrox"){
var div = document.getElementsByClassName('display')[0];
var ptag = div.getElementsByTagName('p')[0];
if(typeof greeting == 'undefined'){
greeting = ptag.innerHTML;
}
ptag.innerHTML = greeting + elementValue;
}
}
document.getElementById('checkbtn').addEventListener('click', topAnswer);
Here is the Demo.
Hey FYI your question does not contain all the HTML, making it very confusing. Thankfully the jsbin does.
I don't think document.write() is the right way, because of this:
Why is document.write considered a "bad practice"?
First, you need to wrap "The top champion you selected is:" in a span with an id.
<span id='bottomText'>The top champion you selected is:</span>
If you want to use pure JavaScript, here is what to do:
http://jsbin.com/EzUNuTUy/1/edit
Taken from here: How to do insert After() in JavaScript without using a library?
<script>
//This function will insert a node after an element
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function topAnswer(){
var element = document.getElementById("topSelect");
var elementValue = element.value;
if(elementValue == "aatrox"){
var el = document.createElement("span");
el.innerHTML = "You selected Aatrox for your teams top lane champion.";
var div = document.getElementById("bottomText");
insertAfter(div, el);
}
}
</script>
If you want to use jQuery, it is really easy:
<script>
function topAnswer(){
var element = document.getElementById("topSelect");
var elementValue = element.value;
if(elementValue == "aatrox"){
$("You selected Aatrox for your teams top lane champion.").insertAfter($("#bottomText"));
}
}
</script>
You seem to be new to HTML/JavaScript, I would definitely recommend learning a library like jQuery. It will make your life much easier.

storing user input in array

I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.

Categories

Resources