Javascript dynamic adding mutiple drop down list - javascript

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.

Related

Create element "datalist"?

How to create datalist dynamically?
Was able to dynamically create a drop down using create element and append child but am struggling with datalist.
<script>
let counter = 0;
function myFunction3() {
if (counter < 5) {
counter++;
/*var text = document.createElement("TEXTAREA");
text.id = "text" + counter;
document.body.appendChild(text);*/
var drdwn = document.createElement("datalist");
drdwn.id = "drdwn" + counter;
document.body.appendChild(drdwn);
var opt1 = document.createElement("option");
opt1.text = "<";
opt1.value = "<";
document.getElementById("drdwn" + counter).appendChild(opt1);
var opt2 = document.createElement("option");
opt2.text = ">";
opt2.value = ">";
document.getElementById("drdwn" + counter).appendChild(opt2);
var opt3 = document.createElement("option");
opt3.text = "=";
opt3.value = "=";
document.getElementById("drdwn" + counter).appendChild(opt3);
/*var value = document.createElement("TEXTAREA");
value.id = "value" + counter;
document.body.appendChild(value);*/
}
}
</script>
const options = document.querySelector('.options');
const datalistCreator = document.querySelector('.datalist-creator');
const datalistsBlock = document.querySelector('.datalists');
let counter = 0;
datalistCreator.addEventListener('click', function() {
const datalist = document.createElement('datalist');
const output = document.createElement('input');
datalist.setAttribute('id', 'datalist' + counter);
output.setAttribute('list', 'datalist' + counter);
output.placeholder = 'Datalist of ' + options.value;
for (let i = 0; i < options.value; i++) {
const option = document.createElement('option');
option.value = i + 1;
datalist.appendChild(option)
}
datalistsBlock.appendChild(datalist);
datalistsBlock.appendChild(output);
counter++;
return output;
})
<input type="text" class="options">
<button class="datalist-creator">Create datalist</button>
<div class="datalists"></div>

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>

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

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 and I guess that the answer variable is the problem because it shows nothing.
var questions = [
{
"question": "L'impact est ",
"option1": "faible",
"option2": "moyen",
"option3": "haut",
},
{
"question": "L'impact2 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');
var chartBar = document.getElementById('bar-horzontal');
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+' ' ;
return;
}
loadQuestion(currentQuestion);
};
loadQuestion(currentQuestion);
In HTML, input elements don't have property textContent so you shouldn't add text inside radio element, you can use span or label.
Also q.opt1 is undefined.
var questions = [{
"question": "L'impact est",
"option1": "faible",
"option2": "moyen",
"option3": "haut"
},
{
"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 lbl_1 = document.getElementById('lbl_1');
var lbl_2 = document.getElementById('lbl_2');
var lbl_3 = document.getElementById('lbl_3');
var nextButton = document.getElementById('nextButton');
var resultCont = document.getElementById('result');
var chartBar = document.getElementById('bar-horzontal');
function loadQuestion(questionIndex) {
var q = questions[questionIndex];
questionEl.textContent = (questionIndex + 1) + '. ' + q.question;
opt1.value = lbl_1.textContent = q.option1;
opt2.value = lbl_2.textContent = q.option2;
opt3.value = lbl_3.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].option1 == answer) {
score1 += 1;
} else if (questions[currentQuestion].option2 == answer) {
score1 += 2;
} else {
score1 += 3
}
selectedOption.checked = false;
currentQuestion++;
progressText.textContent = "Answered: "+(currentQuestion / totQuestions) * 100 + "%";
if (currentQuestion == totQuestions - 1) {
nextButton.textContent = 'Finish';
}
if (currentQuestion == totQuestions) {
nextButton.style.display = 'none';
container.style.display = 'none';
resultCont.style.display = '';
resultCont.textContent = 'le résultat est ' + ' ' + score1 + ' ';
return;
}
loadQuestion(currentQuestion);
};
loadQuestion(currentQuestion);
<div id="quizContainer">
<p id="question"></p>
<input id="opt1" name="option" type="radio"><label for="opt1" id="lbl_1"></label>
<input id="opt2" name="option" type="radio" /><label for="opt2" id="lbl_2"></label>
<input id="opt3" name="option" type="radio" /><label for="opt3" id="lbl_3"></label>
</div>
<br/>
<button id="nextButton" onclick="loadNextQuestion()">Next</button>
<br/>
<p id="progressText"></p>
<div id="bar-horzontal"></div>
<div id="result"></div>
I think you are telling the program to add extra point to option 2 and 3. Look at the code below you are saying to add 2 point if its option 2 and and 3 points if its option 3.
} else if (questions[currentQuestion].opt2 == answer) {
score1 += 2;
} else {
score1 += 3
I think they should be like this.
} else if (questions[currentQuestion].opt2 == answer) {
score1 += 1;
} else {
score1 += 1

dropdown display just js

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!

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