dropdown display just js - javascript

I have a few dropdown lists that are by javascript and it is working fine.
The question is how do I display out the title of the first dropdown.
I have commented on the place that cant work
var h = document.getElementById("createSelect");
var textdisplay = h.options[h.selectedIndex].text;

Create a function which receives an array and a string and return title of spesific item. like this
function getTitle(arr, val) {
var item = arr.find(function(itm) {
return itm['value'] == val;
});
return item['title'];
}
Use this function for array you want. for example title of first array
var textdisplay = getTitle(arr1, fId);
And add that where you want as output
document.getElementById("Result").innerHTML +=
"Answer " +
++answer +
") " +
area +
" ----" +
func(area) +
"<br>" +
amount / discount +
"<br>" +
soilamount +
"<br>" +
textdisplay;
Use this code.
var rowNumber = 0;
var arr1 = [{
title: "10mm",
value: "return 2;"
},
{
title: "20mm",
value: "return 2;"
},
{
title: "30mm",
value: "return 3;"
},
{
title: "40mm",
value: "return 4;"
},
{
title: "title 1",
value: "return Math.min( Math.max(2 / 100 * supposearea + 11.7222222222222, 9.5), 11.5 );"
},
{
title: "title 2",
value: "return Math.min(Math.max(2 / 100 * supposearea + 10.2222222222222, 8), 10);"
},
{
title: "title 3",
value: "return Math.min( Math.max(2 / 200 * supposearea + 11.7222222222222, 9.5), 11.5 );"
},
{
title: "title 4",
value: "return Math.min(Math.max((2/200*supposearea + 13.7222222222222),11.5),13.5);"
}
];
var arr2 = [{
title: "Original",
value: "0.65"
},
{
title: "35% Discount",
value: "1"
}
];
var arr3 = [{
title: "No Soil",
value: "return 0;"
},
{
title: "Soil",
value: "return Math.min(Math.max((2*(areas) + 3), 2),4);"
}
];
function createSelect(tag, id, array) {
var select = document.createElement("select");
select.id = id + "-" + rowNumber;
tag.appendChild(select);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].value;
option.text = array[i].title;
select.appendChild(option);
}
}
function getTitle(arr, val) {
var item = arr.find(function(itm) {
return itm['value'] == val;
});
return item['title'];
}
function add_field() {
var p = document.createElement("p");
p.setAttribute("id", "input_text" + rowNumber + "_wrapper");
var input1 = document.createElement("input");
input1.setAttribute("type", "text");
input1.setAttribute("class", "input_text");
input1.setAttribute("id", "inp1-" + rowNumber);
p.appendChild(input1);
var input2 = document.createElement("input");
input2.setAttribute("type", "text");
input2.setAttribute("class", "input_text");
input2.setAttribute("id", "inp2-" + rowNumber);
p.appendChild(input2);
createSelect(p, 'sel1', arr1);
createSelect(p, 'sel2', arr2);
createSelect(p, 'sel3', arr3);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute(
"onclick",
'remove_field("input_text' + rowNumber + '_wrapper")'
);
p.appendChild(btn);
document.getElementById("field_div").appendChild(p);
rowNumber++;
}
function remove_field(id) {
document.getElementById(id).innerHTML = "";
calculate();
}
function calculate() {
var answer = 0;
document.getElementById("Result").innerHTML = "";
var ps = document.getElementById("field_div").getElementsByTagName("p");
for (var i = 0; i < ps.length; i++) {
if (ps[i].childNodes.length == 0) continue;
var length = ps[i].childNodes[0].value;
var width = ps[i].childNodes[1].value;
var area = length * width;
var fId = ps[i].childNodes[2].value;
var func = new Function("supposearea", fId);
var discount = ps[i].childNodes[3].value;
var funcId = ps[i].childNodes[4].value;
var soil = new Function("areas", funcId);
var amount = area * func(area);
var soilamount = area * soil(area);
// ---- CANNOT WORK
var textdisplay = getTitle(arr1, fId);
// -- PLS CHECK CHECK HERE----------------------------------------------->
var statement;
if (soilamount < 1) {
statement = "Total Impe ";
} else {
statement = "Got Soil";
}
document.getElementById("Result").innerHTML +=
"Answer " +
++answer +
") " +
area +
" ----" +
func(area) +
"<br>" +
amount / discount +
"<br>" +
soilamount +
"<br>" +
textdisplay;
document.getElementById("Result1").innerHTML += statement;
}
}
<div id="wrapper">
<div id="field_div">
<input type="button" value="Grass" onclick="add_field();">
</div>
</div>
<p><button type="button" onclick="calculate()">Calculate</button></p>
<p id="Result"></p>
<p id="Result1"></p>
Tip Use specific ids for your drop downs. I pass a third input for your createSelect function.

I did the following modifications/enhancements in your code:
(I know that doesn't answer the question for the moment, but I am waiting for your clarifications.)
Changed id to className, as you shouldn't have multiple identical ids,
Moved the arrays outside of their functions,
Removed the "duplicate" functions and added a second parameter to the remaining one.
See snippet with my comments for more details:
var rowNumber = 0;
// TAKIT: Moved arrays outside of the functions,
// as the functions were similar we'll be only using one!
// (We could rename those arrays to have a meaningfull variable name)
var array1 = [{
title: "10",
value: "return 10;"
},
{
title: "20",
value: "return 20;"
},
{
title: "30",
value: "return 30;"
},
{
title: "40",
value: "return 40;"
},
{
title: "50",
value: "50;"
},
{
title: "60",
value: "60;"
},
{
title: "70",
value: "70;"
},
{
title: "80",
value: "return Math.min(Math.max((3/-500*supposearea + 103.7),50.5),60);"
}
];
var array2 = [{
title: "Original",
value: "0.65"
},
{
title: "35% Discount",
value: "1"
}
];
var array3 = [{
title: "No Soil",
value: "return 0;"
},
{
title: "Soil",
value: "165.3;"
}
];
// TAKIT: Added 2nd parameter in this function
function createSelect(tag, array) {
var select = document.createElement("select");
select.className = "select-" + rowNumber; // TAKIT: Changed .id to .className
tag.appendChild(select);
// Append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].value;
option.text = array[i].title;
select.appendChild(option);
}
}
// TAKIT: Removed the other createSelect1 and 2 functions, they were similar
function add_field() {
var p = document.createElement("p");
p.setAttribute("id", "input_text" + rowNumber + "_wrapper");
var input1 = document.createElement("input");
input1.setAttribute("type", "text");
input1.setAttribute("class", "input_text");
input1.setAttribute("id", "inp1-" + rowNumber);
p.appendChild(input1);
var input2 = document.createElement("input");
input2.setAttribute("type", "text");
input2.setAttribute("class", "input_text");
input2.setAttribute("id", "inp2-" + rowNumber);
p.appendChild(input2);
// TAKIT: Using the same function for the 3 lines below, with the new 2nd parameter
createSelect(p, array1);
createSelect(p, array2);
createSelect(p, array3);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute("onclick", 'remove_field("input_text' + rowNumber + '_wrapper")');
p.appendChild(btn);
document.getElementById("field_div").appendChild(p);
rowNumber++;
}
function remove_field(id) {
document.getElementById(id).innerHTML = "";
calculate();
}
function calculate() {
var answer = 0;
document.getElementById("Result").innerHTML = "";
var ps = document.getElementById('field_div').getElementsByTagName('p');
for (var i = 0; i < ps.length; i++) {
if (ps[i].childNodes.length == 0) continue;
var length = ps[i].childNodes[0].value;
var width = ps[i].childNodes[1].value;
var area = length * width;
var fId = ps[i].childNodes[2].value;
var func = new Function("supposearea", fId);
var discount = ps[i].childNodes[3].value;
var funcId = ps[i].childNodes[4].value;
var soil = new Function("areas", funcId);
var amount = area * (func(area));
var soilamount = area * (soil(area));
// -- CANNOT WORK -----------------------------------
var h = document.getElementById("createSelect"); // TAKIT: null, because id "createSelect" doesn't exist. What are you trying to do?
var textdisplay = h.options[h.selectedIndex].text;
// -- PLS CHECK CHECK HERE --------------------------
var statement;
if (soilamount < 1) {
statement = "Total Impe ";
} else {
statement = "Got Soil";
}
document.getElementById("Result").innerHTML +=
"Answer " + ++answer + ") " + area + " ----" + func(area) + '<br>' + amount / discount + '<br>' + soilamount + "<br>";
document.getElementById("Result1").innerHTML += statement;
}
}
<div id="wrapper">
<div id="field_div">
<input type="button" value="Grass" onclick="add_field();">
</div>
</div>
<p><button type="button" onclick="calculate()">Calculate</button></p>
<p id="Result"></p>
<p id="Result1"></p>
Feel free to comment for any modification.
Hope it helps, anyway!

Related

Printing an object within an array showing as blank

function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var objEvent = {};
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
arrEvent.push(objEvent);
while(objEvent.name.length > 0) {
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
if(objEvent.name.length > 0) {
arrEvent.push(objEvent);
}
}
displayEvent(arrEvent);
}
window.onload = init;
Trying to print an object array into the HTML paragraph id and whenever I execute the code above I get the correct output but the array elements just show as blank.
You are always pushing the same object into your array.
Change to:
function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var name = '';
var age = '';
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
arrEvent.push({name: name, age: age});
while(name.length > 0) {
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
if(name.length > 0) {
arrEvent.push({name: name, age: age});
}
}
displayEvent(arrEvent);
}
window.onload = init;

Why does score evaluate score +1 when str is set to opt2

I have a function which calculates the score in a survey depending on the chosen option, but I am always getting the same value which is in the first if condition
var questions = [{
"question": "L'impact est ",
option1: "faible",
option2: "moyen",
option3: "haut",
},
var currentQuestion = 0;
var score1 = 0;
var totQuestions = questions.length;
var number = 0;
var progressText = document.getElementById("progressText");
var container = document.getElementById('quizContainer');
var questionEl = document.getElementById('question');
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var nextButton = document.getElementById('nextButton');
var resultCont = document.getElementById('result');
function loadQuestion(questionIndex) {
var q = questions[questionIndex];
questionEl.textContent = (questionIndex + 1) + '. ' + q.question;
opt1.textContent = q.option1;
opt2.textContent = q.option2;
opt3.textContent = q.option3;
progressText.innerText = questionIndex + 1 + ' de ' + totQuestions + '
questions ';
};
function loadNextQuestion() {
var selectedOption =
document.querySelector('input[type=radio]:checked');
if (!selectedOption) {
alert('veuillez sélectionner votre réponse');
return;
}
var answer =selectedOption.Value;
if (questions[currentQuestion].opt1 == answer) {
score1 += 1;
} else if (questions[currentQuestion].opt2 == answer) {
score1 += 2;
} else {
score1 += 3
}
selectedOption.checked = false;
currentQuestion++;
progressText.textContent = questionEl / totQuestions
if (currentQuestion == totQuestions - 1) {
nextButton.textContent = 'Finish';
}
if (currentQuestion == totQuestions) {
container.style.display = 'none';
resultCont.style.display = '';
resultCont.textContent = 'le résultat est ' + ' ' + score1 + ' '
+answer+' '+ option1 ;
return;
}
loadQuestion(currentQuestion);
};
loadQuestion(currentQuestion);
If i understood you well, your problem may be because of one more reason bellow:
You don't trigger change event on your <select> element.
The answer's value, you may need to use .selectedIndex to get the answered value.
Have a look at
onchange Event , .selectedIndex
var questions = [{
opt1: "Answer 1",
opt2: "Answer 2",
opt3: "Answer 3"
}];
// score1, currentQuestion variables defined as example
var currentQuestion = 0;
var score1 = 1;
var sel = document.getElementById("sel");
sel.addEventListener("change", function() {
var answer = this.options[this.selectedIndex].value;
if (questions[currentQuestion].opt1 == answer) {
score1 += 1;
} else if (questions[currentQuestion].opt2 == answer) {
score1 += 2;
} else {
score1 += 3;
}
console.log("score1 = " + score1)
});
<div id="q"></div>
<select id="sel">
<option value="Answer 1">Answer 1</option>
<option value="Answer 2">Answer 2</option>
<option value="Answer 3">Answer 3</option>
</select>

Javascript dynamic adding mutiple drop down list

i want to achieve a dynamic form that will be generated when the button is pressed through javascript. right now only the textbox is working.
this is the drop down list in html and which i want to achieve in js dynamically using button
<form>
<select id="height">
<option value="Math.min(Math.max((2/-900*supposearea + 11.7222222222222),9.5),11.5)">method 1</option>
<option value="Math.min(Math.max((2/-900*supposearea + 10.2222222222222),8),10)">method 2</option>
</select>
</form>
the below is the js
var height = eval(document.getElementById("height").value);
right now i want to put the drop down into the add button code below
function add_field(){
var total_text=document.getElementsByClassName('input_text');
total_text=total_text.length+1;
var p = document.createElement('p');
p.setAttribute('id', 'input_text'+total_text+'_wrapper');
var input1 = document.createElement('input');
input1.setAttribute('type', 'text');
input1.setAttribute('class', 'input_text');
input1.setAttribute('id', 'length'+total_text);
p.appendChild(input1);
var input2 = document.createElement('input');
input2.setAttribute('type', 'text');
input2.setAttribute('class', 'input_text');
input2.setAttribute('id', 'length'+total_text);
p.appendChild(input2);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('value', 'Remove');
btn.setAttribute('onclick', 'remove_field("input_text'+total_text+'")');
p.appendChild(btn);
document.getElementById("field_div").appendChild(p);
}
function remove_field(id){
document.getElementById(id+'_wrapper').innerHTML = '';
}
function calculate(){
var answer = 0;
document.getElementById('Result').innerHTML = '';
var inputs = document.querySelectorAll('input[type=text]');
for(var i = 0; i<inputs.length; ){
var length = inputs[i].value;
var width = inputs[i+1].value;
var area = length*width;
i = i + 2;
document.getElementById('Result').innerHTML += 'Answer '+ ++answer +') ' + area + '<br>';
}
}
<div id="wrapper">
<div id="field_div">
<input type="button" value="Add TextBox" onclick="add_field();">
</div>
</div>
<p><button type="button" onclick="calculate()">Calculate</button></p>
<p id="Result"></p>
i have tried a lot of methods but all of them doesn't seem to work.
Really appreciate to those who can help :)
I did not understand your problem with that drop down and your considered logic for it. But I create this below example, which create dynamic select tag, add its options and also calculate a value depend to its value
function createSelect() {
var select = document.createElement("select");
select.id = "height";
var array = [{
title: "method 1",
value: "f1"
},
{
title: "method 2",
value: "f2"
}
];
document.getElementById("wrapper").appendChild(select);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].value;
option.text = array[i].title;
select.appendChild(option);
}
}
function add_field() {
var total_text = document.getElementsByClassName("input_text");
total_text = total_text.length + 1;
var p = document.createElement("p");
p.setAttribute("id", "input_text" + total_text + "_wrapper");
var input1 = document.createElement("input");
input1.setAttribute("type", "text");
input1.setAttribute("class", "input_text");
input1.setAttribute("id", "length" + total_text);
p.appendChild(input1);
var input2 = document.createElement("input");
input2.setAttribute("type", "text");
input2.setAttribute("class", "input_text");
input2.setAttribute("id", "length" + total_text);
p.appendChild(input2);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute("onclick", 'remove_field("input_text' + total_text + '")');
p.appendChild(btn);
document.getElementById("field_div").appendChild(p);
}
function remove_field(id) {
document.getElementById(id + "_wrapper").innerHTML = "";
}
function f1(supposearea) {
return Math.min(
Math.max(2 / -900 * supposearea + 11.7222222222222, 9.5),
11.5
);
}
function f2(supposearea) {
return Math.min(Math.max(2 / -900 * supposearea + 10.2222222222222, 8), 10);
}
function calculate() {
var answer = 0;
document.getElementById("Result").innerHTML = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length;) {
var length = inputs[i].value;
var width = inputs[i + 1].value;
var area = length * width;
i = i + 2;
document.getElementById("Result").innerHTML +=
"Answer " + ++answer + ") " + area + "<br>";
var fId = document.getElementById("height").value;
if (fId == "f1") {
console.log(f1(area));
} else {
console.log(f2(area));
}
}
}
createSelect();
<div id="wrapper">
<div id="field_div">
<input type="button" value="Add TextBox" onclick="add_field();">
</div>
</div>
<p><button type="button" onclick="calculate()">Calculate</button></p>
<p id="Result"></p>
Also you can use official Function constructor. Your code will be like
var array = [
{
title: "method 1",
value: "return Math.min( Math.max(2 / -900 * supposearea + 11.7222222222222, 9.5), 11.5 );"
},
{
title: "method 2",
value: "return Math.min(Math.max(2 / -900 * supposearea + 10.2222222222222, 8), 10);"
}
];
And Usage
var fId = document.getElementById("height").value;
var func = new Function("supposearea", fId);
console.log(func(area));
Full code
function createSelect() {
var select = document.createElement("select");
select.id = "height";
var array = [{
title: "method 1",
value: "return Math.min( Math.max(2 / -900 * supposearea + 11.7222222222222, 9.5), 11.5 );"
},
{
title: "method 2",
value: "return Math.min(Math.max(2 / -900 * supposearea + 10.2222222222222, 8), 10);"
}
];
document.getElementById("wrapper").appendChild(select);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].value;
option.text = array[i].title;
select.appendChild(option);
}
}
function add_field() {
var total_text = document.getElementsByClassName("input_text");
total_text = total_text.length + 1;
var p = document.createElement("p");
p.setAttribute("id", "input_text" + total_text + "_wrapper");
var input1 = document.createElement("input");
input1.setAttribute("type", "text");
input1.setAttribute("class", "input_text");
input1.setAttribute("id", "length" + total_text);
p.appendChild(input1);
var input2 = document.createElement("input");
input2.setAttribute("type", "text");
input2.setAttribute("class", "input_text");
input2.setAttribute("id", "length" + total_text);
p.appendChild(input2);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute("onclick", 'remove_field("input_text' + total_text + '")');
p.appendChild(btn);
document.getElementById("field_div").appendChild(p);
}
function remove_field(id) {
document.getElementById(id + "_wrapper").innerHTML = "";
}
function calculate() {
var answer = 0;
document.getElementById("Result").innerHTML = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length;) {
var length = inputs[i].value;
var width = inputs[i + 1].value;
var area = length * width;
i = i + 2;
document.getElementById("Result").innerHTML +=
"Answer " + ++answer + ") " + area + "<br>";
var fId = document.getElementById("height").value;
var func = new Function("supposearea", fId);
console.log(func(area));
}
}
createSelect();
<div id="wrapper">
<div id="field_div">
<input type="button" value="Add TextBox" onclick="add_field();">
</div>
</div>
<p><button type="button" onclick="calculate()">Calculate</button></p>
<p id="Result"></p>
Update
I think this is your answer
var rowNumber = 0;
function createSelect(tag) {
var select = document.createElement("select");
select.id = "select-" + rowNumber;
var array = [{
title: "10 Grass",
value: "return 1;"
},
{
title: "20 Grass",
value: "return 2;"
},
{
title: "30 Grass",
value: "return 3;"
},
{
title: "40 Grass",
value: "return 4;"
},
{
title: "1",
value: "return Math.min( Math.max(1212 / -243 * supposearea + 11.7222222222222, 9.5), 11.5 );"
},
{
title: "2",
value: "return Math.min(Math.max(23 / 100 * supposearea + 10.2222222222222, 8), 10);"
},
{
title: "3",
value: "return Math.min( Math.max(342 / 50 * supposearea + 11.7222222222222, 9.5), 11.5 );"
},
{
title: "4",
value: "Math.min(Math.max((244/232134*supposearea + 13.7222222222222),11.5),13.5);"
}
];
tag.appendChild(select);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].value;
option.text = array[i].title;
select.appendChild(option);
}
}
function createSelect1(tag) {
var select = document.createElement("select");
select.id = "select-" + rowNumber;
var array = [{
title: "Original",
value: "0.65"
},
{
title: "10%",
value: "1"
}
];
tag.appendChild(select);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].value;
option.text = array[i].title;
select.appendChild(option);
}
}
function add_field() {
var p = document.createElement("p");
p.setAttribute("id", "input_text" + rowNumber + "_wrapper");
var input1 = document.createElement("input");
input1.setAttribute("type", "text");
input1.setAttribute("class", "input_text");
input1.setAttribute("id", "inp1-" + rowNumber);
p.appendChild(input1);
var input2 = document.createElement("input");
input2.setAttribute("type", "text");
input2.setAttribute("class", "input_text");
input2.setAttribute("id", "inp2-" + rowNumber);
p.appendChild(input2);
createSelect(p);
createSelect1(p);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute("onclick", 'remove_field("input_text' + rowNumber + '_wrapper")');
p.appendChild(btn);
document.getElementById("field_div").appendChild(p);
rowNumber++;
}
function remove_field(id) {
document.getElementById(id).innerHTML = "";
calculate();
}
function calculate() {
var answer = 0;
document.getElementById("Result").innerHTML = "";
var ps = document.getElementById('field_div').getElementsByTagName('p');
for (var i = 0; i < ps.length; i++) {
if (ps[i].childNodes.length == 0) continue;
var length = ps[i].childNodes[0].value;
var width = ps[i].childNodes[1].value;
var area = length * width;
var fId = ps[i].childNodes[2].value;
var func = new Function("supposearea", fId);
var discount = ps[i].childNodes[3].value;
var amount = area * (func(area));
document.getElementById("Result").innerHTML +=
"Answer " + ++answer + ") " + area + " ----" + func(area) + '<br>' + amount / discount + "<br>";
}
}
<div id="wrapper">
<div id="field_div">
<input type="button" value="Grass" onclick="add_field();">
</div>
</div>
<p><button type="button" onclick="calculate()">Calculate</button></p>
<p id="Result"></p>
Hope this helps you.

Removing random element from an array /Javascript

I googled my question but found no answer, thank you in advance for help. The thing is, I have some code that works ok, but I would like to improve it:
function go(times) {
function pick(n) {
return n[Math.floor(Math.random() * n.length)];
}
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
When the random word is picked, it should be removed from an array so there won't be any repeation. I can handle it with splice function if I know exact index of element, but when it's random it doesn't work how I want it to.
You can easily add a function to all arrays to return a random value and/or remove one randomly.
// After this, you can call.getRandomValue() on any array!
Array.prototype.getRandomValue = function(removeItem) {
if (this.length < 1) throw "Cannot get random value from zero-length array";
var randomIndex = Math.floor(Math.random() * this.length);
var randomValue = this[randomIndex];
if (removeItem)
this.splice(randomIndex, 1);
return randomValue;
};
function constructDescription(sentenceCount) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var description = "";
for(var i = 0; i < sentenceCount; i++) {
if (body.length > 0 && adj.length > 0 && word.length > 0) {
description += (description.length > 0) ? " And your " : "Your ";
description += body.getRandomValue(true) + " looks " + adj.getRandomValue(true) + " and " + word.getRandomValue(true) + "!"
}
}
return description;
}
Try it out with a Fiddle here.
Use a different function instead of calling go() recursively in the loop. By calling go() for each phrase you initialize the original arrays each time. Then do the splicing in pick()
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = ''
function pick(n) {
var idx = Math.floor(Math.random() * n.length);
var str = n[idx];
n.splice(idx, 1)
return str;
}
function getPhrase(i) {
var phrase = pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
return i == 0 ? "Your " + phrase : " And your " + phrase;
}
for (var i = 0; i < times; i++) {
str += getPhrase(i);
}
return str;
}
document.body.innerHTML = go(4);
You just need to combine your splice and your randomizer. example:
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function pick(n) {
return n.splice(Math.floor(Math.random() * n.length), 1);
}
var str = "";
for (var i = 0; i < times; i++) {
str += (i > 0 ? " And your ":"Your ") + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
}
return str;
}
#lucounu solution is absolutely spot on.
In case if you just wanted to improve upon your initial solution , you could have done the following :
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function go(times) {
function pick(n) {
var index = Math.floor(Math.random() * n.length)
var randomString = n[index];
n.splice(index,1);
return randomString;
}
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
console.log(go(2));
Give it a try
var data = ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist", "cell", "atom"];
while (data.length) {
document.write(data.splice(data.length * Math.random() | 0, 1)[0] + '<br>');
}

Unexpected end of input JavaScript

Can somebody please tell me what is wrong with the JavaScript in this code? It said "Unexpected end of input", but I do not see any errors. All my statements seem to be ended at some point, and every syntax checker says that no errors were detected.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Slide Editor</title>
<style>
#font-face {
font-family: SegoeUILight;
src: url(Segoe_UI_Light.ttf);
}
* {
font-family: SegoeUILight;
}
</style>
<script src="Slide/RevealJS/lib/js/html5shiv.js"></script>
<script src="Slide/RevealJS/lib/js/head.min.js"></script>
</head>
<body onload="editSlideshow()">
<div id="sl">
<span id="sls"></span>
</div>
<span id="slt"></span>
<div id="editor">
</div>
<script>
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
var name = getURLParameters("show");
var slideCount = 1;
function editSlideshow() {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
slideCount = 1;
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
slideCount = textArray.length;
var slideCnt = textArray.length - 1;
for (var i = 0; i <= slideCnt; i++) {
$("#sls").append('<button onclick = "loadSlide\'' + (i + 1) + '\')" id = "slide_' + (i + 1) + '">Slide ' + (i + 1) + '</button>');
};
$("sl").append('<button onclick = "newSlide()">New Slide</button>');
};
};
function loadSlide(num) {
var array = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (array == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else if (array[num - 1] == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else {
var slideArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = slideArray[num - 1];
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("editTxt").value = text;
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
};
};
function saveSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
var text = document.getElementById("editTxt").value;
var textArray = new Array();
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = document.getElementById("editTxt").value;
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
};
};
function newSlide() {
var nextSlide = slideCount + 1;
$("#sls").append('<button onclick = "loadSlide(\'' + nextSlide + '\')" id = "slide_' + nextSlide.toString() + '">Slide ' + nextSlide.toString() + '</button>');
slideCount = nextSlide;
};
function deleteSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
textArray.splice((num - 1), 1);
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
};
};
</script>
</body>
</html>
You've gotten the punctuation wrong in more than one of your onclick attributes, for instance here:
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
It's missing the opening parenthesis. The reason syntax checks don't immediately catch this is because you're putting code inside a string. Which you should not do.
Since you're using jQuery, how about using .click(function() { ... }) instead of inline attributes? Just be careful to get your captured variables correct.
The problem at line 63
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
Should be:
$("#sl").append('<button onclick = "newSlide()">New Slide</button>');

Categories