Ok this is a bit complicated. Basically I populate a select with an array. Then, I want to create another select, and populate it with the same array again. I believe that the populate function is not called properly when a new select is created, but I cannot find when to call it, to populate the created select.
1st: I query my db to get some member names, and use json_encode my resulting array, to create a json array.
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
$json_array = json_encode($result_array);
then I echo that array to a javascript array, and populate a select tag with the result. All this happens on window load.
<script>
var members = <?php echo $json_array; ?>;
function populate()
{
var sel = document.getElementById('members');
var fragment = document.createDocumentFragment();
members.forEach(function(member, index) {
var opt = document.createElement('option');
opt.innerHTML = member;
opt.value = member;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
}
window.onload = populate;
</script>
The html div containing the select:
<div id="Members">
<select id="members"></select>
</div>
<input type="button" value="+" onClick="addInput('Members'); populate();">
and then I use another script to create more divs
<script>
var counter = 1;
var limit = 3;
function addInput(divName)
{
if (counter == limit)
{
var message = document.getElementById("linkLimit");
message.innerHTML = "Maximum amount of links reached";
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<select id='members'></select>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
However, the resulting selects are never actually populated. I believe that the populate function is not called properly, but I cannot find when to call it, to populate the created select.
Alternatively, for a static amount of select inputs, I tried doing
<div id="Members">
<select id="members" name="members"></select>
<select id="members1" name="members"></select>
<select id="members2" name="members"></select>
</div>
but again, only the first select is populated
By using a for loop and giving members, members1, members2 through an array, all three lists are populated, however, this is not so functional, since I can't know how many members the user will want to select
Related
I am trying to create a button that calls a function which creates new list items with selection boxes. The code below create a select element however, the button disappears and it doesn't create one list item after another. Any idea how I can persist the button and add one select element after another?
<button type="button" onclick="createTable()">Add Item</button>
function createTable()
{
var itemName = "Selections: ";
document.write(itemName);
for (var i=0;i<7;i++)
{
var myTable = " ";
myTable+="<select name='test' id='mySelect"+i+"' style='font-size:10px' onchange='Calculate()'>";
myTable+="<option value='zeroPoint'>0</option>";
myTable+="<option value='halfPoint'>1/2</option>";
myTable+="<option value='onePoint'>1</option>";
myTable+="</select>";
document.write(myTable);
}
}
I made some changes to the documnet.write way you have. However, I would strongly recommend dynamically creating html dom nodes. I added another method, createTable2, which does the required. It will also be easier for you to preserve the html content you have, which can be easily written over with document.write way.
Edit:
I added one more method, createTable2, to allow adding multiple selects. There is a model you can pass in with the select and option information you have. There is a flag, empty, which is set to true if you would like to empty the div before adding new selects; i.e. createTable3(true).
function createTable()
{
var itemName = "Selections: ";
var selectElement = document.getElementById("render");
for (var i=0;i<7;i++)
{
var myTable = " ";
myTable+="<select name='test' id='mySelect"+i+"' style='font-size:10px' onchange='Calculate()'>";
myTable+="<option value='zeroPoint'>0</option>";
myTable+="<option value='halfPoint'>1/2</option>";
myTable+="<option value='onePoint'>1</option>";
myTable+="</select>";
selectElement.innerHTML = myTable;
}
}
function createTable2(){
var myDiv = document.getElementById("render");
//Create array of options to be added
var array = ["zeroPoint","halfPoint","onePoint"];
var texts = ["1","1/2","1"];
var selectList = document.createElement("select");
selectList.id = "mySelect";
selectList.style.fontSize = "10px";
selectList.onChange = 'Calculate()';
myDiv.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = texts[i];
selectList.appendChild(option);
}
}
function createTable3(empty){
var myDiv = document.getElementById("render");
if(empty){
myDiv.innerHTML = "";
}
let model = {
"select1": [{value: "zeroPoint", label: "1"},
{value: "halfPoint", label: "1/2"},
{value: "onePoint", label: "1"}],
"select2": [{value: "zeroPoint1", label: "11"},
{value: "halfPoint1", label: "11/22"},
{value: "onePoint1", label: "11"}]
};
Object.keys(model).forEach(function(key){
let entry = model[key];
var selectList = document.createElement("select");
selectList.id = key;
selectList.style.fontSize = "10px";
myDiv.appendChild(selectList);
//Create and append the options
for (var i = 0, item; item = entry[i]; i++) {
var option = document.createElement("option");
option.value = item.value;
option.text = item.label;
selectList.appendChild(option);
}
});
}
<button type="button" onclick="createTable3()">Add Item</button>
<div id= "render"/>
If you use document.write("") the entire web page content will be replace by the content you pass inside the document.write function. Instead create a div element under button element like
<div id="list"></div>
then in the javascript file change as
function createTable()
{
var itemName = "Selections: ";
var selectElement = document.getElementById(list);
for (var i=0;i<7;i++)
{
var myTable = " ";
myTable+="<select name='test' id='mySelect"+i+"' style='font-size:10px' onchange='Calculate()'>";
myTable+="<option value='zeroPoint'>0</option>";
myTable+="<option value='halfPoint'>1/2</option>";
myTable+="<option value='onePoint'>1</option>";
myTable+="</select>";
selectElement.innerHTML = myTable;
}
}
I am unsure what you are exactly trying to achieve, but having DOM elements in strings and then modifying an elements innerHTML or using document.write is just a hack. You need to leverage the DOM apis.
While that means my code is maybe double or triple the the size of your code. Its the more maintainable version long term.
function createTable() {
var selectMenu = document.querySelector('#selectionsContainer');
// Array of options elements
var myTable = [];
// Pushing some elements to our my table array
//
myTable.push(
createOption('zeroPoint', 0),
createOption('halfPoint', 0.5),
createOption('onePoint', 1)
)
// Looping through all elements and adding them to the //selections container
//
myTable.forEach( element => {
selectionsContainer.appendChild(element);
});
}
/** Creates an option element and returns it for usage */
function createOption(value, label) {
var option = document.createElement('option');
option.value = value;
option.innerText = label;
return option;
}
function Calculate(value) {
console.log('do whatever you want to with the value: ', value);
}
select {
font-size:10px
}
<button type="button" onclick="createTable()">Add Item</button>
<label for="selectionsContainer">
Selections
<label>
<select id="selectionsContainer" onchange='Calculate(this.value)'>
<option value=5> 5 </option>
<select>
All the answers so far are pointing that OP might be doing something wrong by not creating select dynamically. But we don't know his requirements.
Also everybody already explained document.write will write on you entire document thus deleting everything, you don't want that.
document.write --> https://developer.mozilla.org/en-US/docs/Web/API/Document/write
appendChild should be used but you wanted a string and appendChild expect Node not string.
appendChild --> https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
node --> https://developer.mozilla.org/en-US/docs/Web/API/Node
So the only way to solve this is by using innerHTML and summing up inner Html by adding new ones.
Or by creating node from sting, which requires some more logic, see here --> Creating a new DOM element from an HTML string using built-in DOM methods or prototype
innerHTML --> https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
const selectTamplate = (selectId, onChangeCallbackName) => {
return `
<select name='test' id='mySelect${selectId}' style='font-size:10px' onchange='${onChangeCallbackName}()'>
<option value='zeroPoint'>0</option>
<option value='halfPoint'>1/2</option>
<option value='onePoint'>1</option>
</select>
`
};
const appendStringHtml = (elementTargetHtml, elemenAppend) => {
elemenAppend.innerHTML += elementTargetHtml;
}
const doSomethingOnChange = () => {
console.log('I am the KING!');
};
const placeToAppend = document.querySelector('.append-selects-here');
const buttonAppender = document.querySelector('.btn-append');
let selectID = 1;
buttonAppender.addEventListener('click', ()=>{
const selectHTML = selectTamplate(selectID, 'doSomethingOnChange');
appendStringHtml(selectHTML, placeToAppend);
selectID ++;
});
<button class="btn-append">Add Selects</button>
<div class="append-selects-here"></div>
see the working code here --> https://codepen.io/nikolamitic/pen/PEpEbj
I used template string so that interpolation is possible, little bit more clear. And separate the logic while still keeping yours.
I have this problem here
The problem has been solved, but my question is how can I get the second value from that, or the third one. The sheet will have many tables and at some point I will need a total for each table. Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense.
Thank you!
Kind regards,
L.E. Test file
If I understood your question correctly, instead of breaking the loop when a match to "Total" is found do whatever is needed to be done within the loop like so...
var today = toDateFormat(new Date());
var todaysColumn =
values[5].map(toDateFormat).map(Number).indexOf(+today);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1",
"dd/MM/yyyy");
for (var i=0; i<values.length; i++){
if (values[i][0]=='Total'){
nr = i;
Logger.log(nr);
var output = values[nr][todaysColumn];
// Do something with the output here I"m assuming you email it
}
}
The loop will keep going and find every "Total" and do the same thing. This answer assumes that the "Totals" are in the same column. You can get fancier with this if you only want certain tables to send and not others, but this should get you started.
I didn't quite understand the second part of your question...
"Also, is there any solution to automatically find the the array
number which contain date row for each table (instead defining this
manually). Hope my explanation make sense."
I'm guessing you want all the rows that contain "Total" in the specific column. You could instantiate a variable as an empty array like so, var totals = [];. Then instead of sending the email or whatever in the first loop you would push the row values to the array like so, totals.push(nr+1) . //adding 1 gives you the actual row number (rows count from 1 but arrays count from 0). You could then simply loop through the totals array and do whatever you wanted to do. Alternatively you could create an array of all the values instead of row numbers like totals.push(values[nr][todaysColumn]) and loop through that array. Lots of ways to solve this problem!
Ok based on our conversation below I've edited the "test" sheet and updated the code. Below are my edits
All edits have been made in your test sheet and verified working in Logger. Let me know if you have any questions.
Spreadsheet:
Added "Validation" Tab
Edited "Table" tab so the row with "Email Address" in Column A lines up with the desired lookup values (dates or categories)...this was only for the first two tables as all the others already had this criteria.
Code:
Create table/category selector...
In the editor go to File >> New >> HTMLfile
Name the file "inputHTML"
Copy and paste the following code into that file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form class="notice_form" autocomplete="off" onsubmit="formSubmit(this)" target="hidden_iframe">
<select id="tables" onchange="hideunhideCatagory(this.value)" required></select>
<p></p>
<select id="categories" style="display:none"></select>
<hr/>
<button class="submit" type="submit">Get Total</button>
</form>
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// The code in this function runs when the page is loaded.
$(function() {
var tableRunner = google.script.run.withSuccessHandler(buildTableList);
var catagoryRunner = google.script.run.withSuccessHandler(buildCatagoryList);
tableRunner.getTables();
catagoryRunner.getCategories();
});
function buildTableList(tables) {
var list = $('#tables');
list.empty();
list.append('<option></option>');
for (var i = 0; i < tables.length; i++) {
if(tables[i]==''){break;}
list.append('<option>' + tables[i] + '</option>');
}
}
function buildCatagoryList(categories) {
var list = $('#categories');
list.empty();
list.append('<option></option>');
for (var i = 0; i < categories.length; i++) {
if(categories[i]==''){break;}
list.append('<option>' + categories[i] + '</option>');
}
}
function hideunhideCatagory(tableValue){
var catElem = document.getElementById("categories");
if(tableValue == "Total Calls By Date" || tableValue == "Total Appointments by Date"){
catElem.style.display = "none"
document.required = false;
}else{
catElem.style.display = "block"
document.required = true;
}
}
function formSubmit(argTheFormElement) {
var table = $("select[id=tables]").val(),
catagory = $("select[id=categories]").val();
console.log(table)
google.script.run
.withSuccessHandler(google.script.host.close)
.getTotal(table,catagory);
}
</script>
</body>
<div id="hiframe" style="display:block; visibility:hidden; float:right">
<iframe name="hidden_iframe" height="0px" width="0px" ></iframe>
</div>
</html>
Edits to Code.gs file
Replace code in Code.gs with this...
//This is a simple trigger that creates the menu item in your sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Run Scripts Manually')
.addItem('Get Total','fncOpenMyDialog')
.addToUi();
}
//This function launches the dialog and is launched by the menu item
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('inputHTML')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Select table to get total for');
};
//main function called by clicking "Get Total" on the dialogue...variables are passed to this function from the formSubmit in the inputHTML javascript
function getTotal(table,catagory) {
function toDateFormat(date) {
try {return date.setHours(0,0,0,0);}
catch(e) {return;}
}
//get all values
var values = SpreadsheetApp
.openById("10pB0jDPG8HYolECQ3eg1lrOFjXQ6JRFwQ-llvdE2yuM")
.getSheetByName("Tables")
.getDataRange()
.getValues();
//declare/instantiate your variables
var tableHeaderRow, totalRow, tableFound = false;
//begin loop through column A in Tables Sheet
for (var i = 0; i<values.length; i++){
//test to see if values have already been found if so break the loop
if(tableFound == true){break;}
//check to see if value matches selected table
if (values[i][0]==table){
//start another loop immediately after the match row
for(var x=i+1; x<values.length; x++){
if(values[x][0] == "Email Address"){ //This header needs to consistantly denote the row that contains the headers
tableHeaderRow = x;
tableFound = true;
}else if(values[x][0] == "Total"){
totalRow = x;
break;
}
}
}
}
Logger.log("Header Row = "+tableHeaderRow)
Logger.log("Total Row = "+ totalRow)
var today = toDateFormat(new Date())
var columnToTotal;
if(catagory==''){
columnToTotal = values[tableHeaderRow].map(toDateFormat).map(Number).indexOf(+today);
}else{
columnToTotal = values[tableHeaderRow].indexOf(catagory);
}
var output = values[totalRow][columnToTotal];
Logger.log(output);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy");
//here is where you would put your code to do something with the output
}
/** The functions below are used by the form to populate the selects **/
function getTables(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var tabelCol = (cSheetHeader.indexOf("Tables")+1);
var tables = cSheet.getRange(2,tabelCol,cSheet.getLastRow(),1).getValues();
return tables.filter(function (elem){
return elem != "";
});
}
function getCatagories(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var catagoriesCol = (cSheetHeader.indexOf("Catagory")+1);
var catagories = cSheet.getRange(2,catagoriesCol,cSheet.getLastRow(),1).getValues();
return catagories.filter(function (elem){
return elem != "";
});
}
I'm currently trying to do a survey system. I have a dynamic dropdown that displays one column 'questiontitle' from my table database. Here's my code of displaying the 'questiontitle' in the dropdown.
<?php
$query=mysqli_query($con, "SELECT * FROM question");
while($row=mysqli_fetch_array($query))
{
?>
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
<?php
}
?>
echo "</select>";
And here's my database table.
My main question is how do I display the 'Option_1 to Option_10 columns' depending on the 'answer_type' column when a data is clicked from the dropdown in real time without refreshing the page? Like if the 'answer_type' is checkbox, it will display the option1-10 as checkbox and if it's radiobutton, it will display the option1-10 as radiobuttons.
There is a lot work to be done to achieve what you want to do. But I can give you a small snippet which you can use to start.
What you still have to do is
Show a page with all questions in the select box. This is done in PHP
checking how ajax works. Expand the showQuestion() function with ajax functionality so your question & answer data is retrieved from the server. this is a good read. When you got your answer, call the appropriate function to display your question and answers. OR store all your information locally...
add a button so that you can send the answers to the server. Listen to the click event and send data (small modifications are required to what I have wrote though) to the server (read the link that I have shown in point 2)
// question object
var questions = {
json1: {
questiontitle: 'How frequently ...',
answertype: 'radiobutton',
options: ['Heavy user', 'serious user', 'regular user', 'light user']
},
json2: {
questiontitle: 'What part of the day...',
answertype: 'checkbox',
options: ['Morning', 'Afternoon', 'Early evening', 'lat evening']
},
json3: {
questiontitle: 'To what extend does the ...',
answertype: 'radiobutton',
options: ['1-5 times', '6-10 times', '> 10 times']
}
};
// function that adds the "questions" input elements to the container
function insertToQuestionBox(els) {
var box = document.getElementById('questionBox');
// cleanup box
while(box.firstChild) box.removeChild(box.firstChild);
// populate with els
for(var i = 0; i < els.length; ++i) box.appendChild(els[i]);
}
// creates the input element based on args
function createInput(type, name, text) {
var i = document.createElement('input');
i.type = type;
i.name = name;
var l = document.createElement('label');
l.textContent = text;
var s = document.createElement('section');
s.appendChild(l);
s.appendChild(i);
return s;
}
// create element with question in it
function createQuestionEl(question) {
var s = document.createElement('span');
s.textContent = question;
return s;
}
// function that is called if the question is of type radio
function handleRadioButtons(data) {
var inputs = [];
inputs.push(createQuestionEl(data.questiontitle));
for(var i = 0; i < data.options.length; ++i) {
inputs.push(createInput('radio', 'rraaddioo', data.options[i]));
}
insertToQuestionBox(inputs);
}
// create checkboxes
function handleCheckboxes(data) {
var inputs = [];
inputs.push(createQuestionEl(data.questiontitle));
for(var i = 0; i < data.options.length; ++i){
inputs.push(createInput('checkbox', 'nana' + i, data.options[i]));
}
insertToQuestionBox(inputs);
}
// gets called each time the drop down has changed
function showQuestion() {
var data = questions[this.value];
switch(data.answertype) {
case 'radiobutton': handleRadioButtons(data); break;
case 'checkbox': handleCheckboxes(data); break;
// todo when default? error ?
}
}
// listen to select changes
document.getElementById('showQuestion').addEventListener('change', showQuestion);
<select id="showQuestion">
<option>please choose</option>
<option value="json1">show json1</option>
<option value="json2">show json2</option>
<option value="json3">show json3</option>
</select>
<div id="questionBox"></div>
On select box change event pass questionid to server side and query your database for answer_type and options and in that method add a condition
$options = '';
if(anwsertype=='radio') {
$options .= <input type="radio" /> Your option
} else {
$options .= <input type="checkbox" />Your option
}
The above condition should be in a loop for each option.
I'm trying to substitute the code that uses javascript and arrays which are visible in source code.
I want to be able to create this with php arrays, or use AJAX and have it stored in another file. I don't know how to make the proper php commands or arrays
var cars= new Array();
cars["OTHER"] = new Array("Heavy Machinery","Semi-Truck","Pickup Truck","Sedan","SUV","Misc");
cars["ATV"] = new Array("small","large");
cars["Boat"] = new Array("Under 20 Feet","Over 20 Feet");
cars["Motorcycle"] = new Array("250CC","500CC","700CC","900+");
cars["RV"] = new Array("Under 25 Feet","Over 25 Feet","5th Wheel");
cars["AC"] = new Array("Cobra");
cars["Acura"] = new Array("1.6 EL","1.7 EL","2.3 CL","2.5 TL","3.0 CL","3.2 TL","3.5 RL","CL","CSX","EL","ILX","Integra","Legend","MDX","NSX","NSX-T","RDX","RL","RSX","SLX","TL","TSX","Vigor","ZDX");
cars["Alfa Romeo"] = new Array("145","146","147","155","156","159","164","166","33","75","308","1900","2600","4C","6C","8C","Alfasud","Alfetta","Berlina","Bimotore","Canguro","Corsa","Disco Volante","Duetto","G1","GT","GTV","GTV-6","GTV6","Giulia","Guiletta","GP","Grand Prix","GTA","Iguana","Junior Z","Milano","Montreal","Navajo","P1","P2","P3","Quadrifoglio","RL","RM","Scarabeo","Spider","Sports Car","Sportwagon","Stradle","Tipo","Torpedo");
........................ALL OTHER MAKES AND MODELS ARE IN BETWEEN........................
cars["Yugo"] = new Array("55","Cabrio","GV");
jQuery(document).ready(function($){
$('span.text select').change(function(){
$(this).siblings('.value').text($(this).find('option[value="'+$(this).val()+'"]').text());
});
for ( make in cars )
{
$('#formmake').append('<option value="'+make+'">'+make+'</option>');
}
$('#formmake').change(function(){
var val = $(this).val();
$('#formmodel').html('<option value="">Select Model</option>');
for ( i in cars[val] )
{
$('#formmodel').append('<option value="'+cars[val][i]+'">'+cars[val][i]+'</option>');
}
$('#formmodel').append('<option value="Other">- Other -</option>');
});
$('#formmake, span.text select').each(function(){
var def = $(this).siblings('.value').text();
$(this).find('option[value='+def+']').attr('selected', 'selected');
$(this).change();
});
});
---------------------- this is what i want to do to HIDE the source on the site --------------------
here is my php to get the MAKE but how do I create the model array so that when a user chooses a car the appropriate MODELS will populate in the corresponding dropdown (called Select Model: )
<?php
$car_make = array('ATV','Boat','Motorcycle','Acura','Alfa Romeo','AM General'); //this is only a partial array, it will have all the makes
echo '<select name="car_make">';
for($i = 0; $i < count($car_make);$i++)
{
echo '<option value="'. ($i + 1) . '">' . $car_make[$i] . '</option>';
}
echo '</select>';
?>
how do i create a second array with vehicle models that will use the first array's option value to lookup a make and then pull the corresponding make's from the model array ?
Well you can use jQuery to select the value of the first select menu and then use it to compare with the specific value for make and then display its specific models
var model=new Array();
function getmodel() {
var make=$('select[name=make]').val();
if(make==='toyota'){$("select[name=model]").html('');$("select[name=model]").append("<option value='corolla'>Corolla</option><option value='camry'>Camry</option><option value='hilux'>Hilux</option>");}
if(make==='honda'){$("select[name=model]").html('');$("select[name=model]").append("<option value='civic'>Civic</option><option value='jazz'>Jazz</option><option value='accord'>Accord</option>");}
if(make==='suzuki'){$("select[name=model]").html('');$("select[name=model]").append("<option value='cultus'>Cultus</option><option value='vitara'>Vitara</option>");}
if(make==='bugatti'){$("select[name=model]").html('');$("select[name=model]").append("<option value='veyron'>Veyron</option><option value='chiron'>Chiron</option>");}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SELECT MAKE:
<select name='make' onchange='getmodel();'>
<option value='toyota'>TOYOTA</option>
<option value='honda'>HONDA</option>
<option value='suzuki'>SUZUKI</option>
<option value='bugatti'>BUGATTI</option>
</select>
<br/>
SELECT MODEL
<select name='model'>
</select>
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.