Deleting items stored - javascript

I'm creating a multiple choice quiz which allows users to insert their own questions and answers and from there create a quiz. I can't think how I could let users delete questions stored in the question bank.
bodyText = bodyText + '<p>Questions currently in the question bank:</p>';
bodyText = bodyText + '<ul>';
for(var i=0; i<questionBank.length;i++) {
// loop through the quiz bank and display each question text for review
bodyText = bodyText + '<li>' + questionBank[i]['questionText'] + '</li>';
}
bodyText = bodyText + '</ul>';
bodyText = bodyText + '<p>Create the quiz, delete or add more questions. </p>';
}

If you also create a button to attached an action too, you can capture the [i] and use it to splice, remove, push, pop, whichever you choose.
bodyText = bodyText + '<p>Questions currently in the question bank:</p>';
bodyText = bodyText + '<ul>';
for(var i=0; i<questionBank.length;i++) {
// loop through the quiz bank and display each question text for review
bodyText = bodyText + '<li>' + questionBank[i]['questionText'] + '</li>'
<button onClick={delete questionBank[i]}>Delete me</button>;
}
bodyText = bodyText + '</ul>';
bodyText = bodyText + '<p>Create the quiz, delete or add more questions. </p>';
}
my button is sudo code!!! It sounds like you might be new to programming, have fun with this. The basic idea is inside that for loop, you can use the [i] or index for each item you're rendering.

Related

How to add new <li> element each click?

First attempt at any sort of Javascript so be gentle aha
Have managed to have the page add the new list item to the inner html of an unordered list, but each time after that it just replaces the initial.
I feel like I'm missing something really basic here?
Any advice would be greatly appreciated.
<script>
function addItem() {
var item = document.getElementById("task-field").value;
document.getElementById("task-list").innerHTML = "<li> " + item + " </li>";
}
</script>
Use
document.getElementById("task-list").innerHTML += "<li> " + item + " </li>";
instead of
document.getElementById("task-list").innerHTML = "<li> " + item + " </li>";
The += operator will use the current value of innerHTML and append your new content in this case. This as suggested by #Hassam Imam.
Another way of doing it is using appendChild() creating the new <li> item through JS. Like this:
function addItem() {
let item = document.getElementById("task-field").value;
let parent = document.getElementById("task-list");
// Create new node.
let li_item = document.createElement("li");
li_item.innerHTML = item;
// Append child.
parent.appendChild(li_item);
}
But this last method is probably too lengthy. The += solution seems good. Just another way of doing it.
<script>
function addItem(item) {
const li = document.createElement('li');
li.innerHTML = `${item}`;
li.id = 'task-field';
document.getElementById('task-list').appendChild(li);
}
</script>

How to edit a one dimentional array via input form

I have written an array to capture a SharePoint input field and add the entry time with JavaScript and then set a history field to the value of the array. This works fine. However, I would now like to be able to edit (and delete) the entries in this array via an edit form, but cannot seem to understand how the pick out the specific entry.
I have tried using splice but that doesn't seem to work. I was able to get the delete to work, but it just deleted the last object in the array, not the specific one that I wanted to delete. I have reviewed w3schools on this topic but I guess it is not sinking in. I will have no idea what the user enters, so its not like I can hard code something like the examples on that site.
//this is adds a button under the statusupdate field. The button will add the status updates to the status history field.
function loadhistory() {
historyform = "<table id=\'TTTT\' style=\'padding:1px;border- collapse:collapse;width:800px;vertical-align:text-top;border:2px\'>"
historyform += "<tr><td colspan=3><div><button type=\'button\' id=\'add2\' style=\'font-weight:bold;\' onclick=\'statusupdatehistory ();\'>Add History</button></div></td></tr></TABLE>";
jQuery("#historyforms").html(historyform);
} //End Load Form
loadhistory();
// builds the array to store the status updates in.
var myArray = new Array();
function statusupdatehistory() {
var entryTime2
entryTime2 = moment.tz('America/New_York').format('M/D/YY h:mm A z');
var etime = entryTime2
//this is the update number. It is manually entered when sending the full form communication. Maybe this can be set to i++ then
// update the ffcUpdate field. This would prevent the miscounting of the update forms. It could i++ when the status update is added
//var updatenumber= getFieldValue("ffcUpdate");
// && statusupdate.trim()!=''
var statusupdate = getFieldValue("ffcStatusUpdate");
if (!(typeof statusupdate === 'undefined') || statusupdate!=null || statusupdate ==='') {
// myArray.push("<tr><td>"+ entryTime2 +"</td>"+" "+"<td>"+ statusupdate + "</td></tr>");
myArray.unshift(etime +"<td>"+ statusupdate);
}
setFieldValue("ffcStatusHistory", myArray.join("|"));
buildhistorytable ();
} // end function
function loadHistoryrecord () {
// alert("Whoops,this feature is not ready just yet!")
};
function delHistoryrecord () {
alert("Whoops,this feature is not ready just yet!")
// myArray.splice(1, 1);
// setFieldValue("ffcStatusHistory", myArray.join("|"));
// buildhistorytable ();
};
// console.log(myArray);
// //document.getElementById('dffs_ffcStatusUpdate').value = '';
function buildhistorytable () {
myArray = getFieldValue("ffcStatusHistory", true).split("|");
historytable = "<table cellspacing=\"0\" cellpadding=\"0\" sytle=\'width:692px;padding-left:10px;padding-right:10px;margin:10px;\'>";
historytable += " <tbody>"
historytable += " <tr>"
historytable += " <table class=\"tbl_border_blk_3b\" style=\"width:700px;font-weight:normal;font-family:Calibri;color:black;font- size:11pt\" align=\'left\'>"
historytable += " <th bgcolor=\"#6699CC\"colspan=4 style=\"width:692px;font-weight:normal;font-family:Calibri;color:black;font- size:11pt;text-align:center;\" >Update History</th>"
//historytable += " <tr style=\'font- weight:bold;color:white; background-color:#123456;text-align:center; padding:10px;\'><td width=\'25%\'>Entered Time</td><td>Status Update</td><td width=\'15%\'>Edit</td><td width=\'17%\'>Delete</td></tr>";
historytable += " <tr style=\'font- weight:bold;color:white; background-color:#123456;text-align:center; padding:10px;\'><td width=\'25%\'>Entered Time</td><td>Status Update</td></tr>";
historytable += " <tbody>"
if (myArray == null || myArray == undefined) {
historytable += "<tr><td colspan=4>There are no Status updates</td></tr>";
} else {
for (var i = 0, len = myArray.length; i < len; i++) {
historytable += "<tr id=\'row" + i + "\'>";
historytable += "<td>" + myArray[i] + "</td>";
//Edit
historytable += "<td width=10%><div style=\'text- align:center\'><a href=\'javascript:loadHistoryrecord(" + i + ")\'><i class='fas fa-edit' style='font-size:27px;color:green'></i></a></div></td>";
//Delete
historytable += "<td width=10%><div style=\'text- align:center\'><a href=\'javascript:delHistoryrecord(" + i + ")\'><i class='fas fa-trash-alt' style='font- size:27px;color:red'></i></a></div></td>";
historytable += "</tr>"
} //End For
} //End if
//historytable += " <br>"
historytable += " </tbody>"
historytable += " </table>"
historytable += " </tbody>"
historytable += "</table>";
jQuery("#historytables").html(historytable);
};
buildhistorytable ();
So if I had 5 entries in my status update field, and I wanted to modify the 3rd entry, how would I pluck just that entry out of the array to edit it?
Quoting from question:
However, I would now like to be able to edit (and delete) the entries
in this array via an edit form, but cannot seem to understand how the
pick out the specific entry.
I am bit confused to work on your code(sorry), instead providing a sample code performing what you asked for:
I have tried using splice but that doesn't seem to work
Lets use splice and indexOf to remove an item:
var arr=[3,5,7,9,11,13];
//lets remove 5:
var index=arr.indexOf(5);
if(index!==-1)
{
arr.splice(index,1); //you want to remove only one element
}
console.log(arr);
This will remove 5 from your array.
To pluck and edit an item:
lets edit value of 9.
var index=arr.indexOf(9);
if(index!==-1)
{
arr[index]=99; //your value
}
console.log(arr);
Just copy paste the code in browser console to see output.
P.S: I just focused how to edit and delete an specific element as your mentioned, that's why I didn't work with your code. Hope this helps.

How do I create a div and give it an ID based on a changing variable?

I'm making a quiz. The user decides how many questions he wants to answer.
A function then takes this number and runs a loop to make an individual question div for each question. The quiz shows a Chinese character and the user has to pick the correct translation.
My code:
var fillInQuestion = function() {
questionDivIdHTML = 'question' + questionNum;
/****************************************
How do I make this Div's ID = to questionDivIdHTML?
// Creates question div
$('#questionArea').append("<div class='questionDiv'></div>");
//$('#questionArea:last-child').attr("id", questionDivIdHTML); <-- NOT WORKING
***************************************/
// Sets up a choice bank.
var choices = [];
// choices will be chosen from this.
var tempAnswerSet = allChoices.slice(0);
//find random item in the database for the question
var thisQuestion = allQuestions[Math.floor(Math.random() * allQuestions.length)];
// add that item to choices
choices.push(thisQuestion);
// remove item from 'database' so it cannot be used in another question
allQuestions.splice(allQuestions.indexOf(thisQuestion), 1);
// remove item from tempAnswer set so it can only be one choice
tempAnswerSet.splice(tempAnswerSet.indexOf(thisQuestion), 1);
// add three more items from the database (incorrect items)
var i = 3;
for (i; i > 0; i--) {
var addChoice = tempAnswerSet[Math.floor(Math.random() * tempAnswerSet.length)];
choices.push(addChoice);
// remove the one selected each time so they cant be chosen again
tempAnswerSet.splice(tempAnswerSet.indexOf(addChoice), 1);
//console.log("choices length: " + choices.length);
}
// shuffle the array
choices.shuffle();
// fill in the div with choices.
$('#questionDivIdHTML').append("Here is an question prompt:" + thisQuestion.english + " <br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[0].hanyu</script>'></input>" + choices[0].hanyu + "<br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[1].hanyu</script>'></input> " + choices[1].hanyu + "<br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[2].hanyu</script>'></input> " + choices[2].hanyu + "<br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[3].hanyu</script>'></input> " + choices[3].hanyu + "<br>");
};
var fillOutQuiz = function() {
for (questionAmount; questionAmount > 0; questionAmount--) {
fillInQuestion();
questionNum += 1;
}
};
I've gotten this code to work, but I broke it, when trying to add the dynamic ID and loop it.
You are saying that this portion of code is not working:
$('#questionArea').append("<div class='questionDiv'></div>");
$('#questionArea:last-child').attr("id", questionDivIdHTML);
Well, it does not work because the :last-child pseudo selector is used incorrectly (see below). It should be:
$('#questionArea').append("<div class='questionDiv'></div>");
$('#questionArea > :last-child').attr("id", questionDivIdHTML);
Or better, you can rearrange your code like this:
$("<div class='questionDiv'></div>")
.attr("id", questionDivIdHTML)
.appendTo("#questionArea");
#questionArea:last-child selects an element with id = questionArea which is also the last child of its parent
#questionArea > :last-child selects the last child of an element with id = questionArea

Generate a list [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
So I want to generate a list from an Array I wrote the following code:
function list() {
table = new Array("Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir");
document.write('<select id="list1" size=6><option value="Rabat">Rabat</option><option value="Casablanca">Casablanca</option></select>');
}
It works but I'm wondering if there's a better coding
You can use a loop to go through all items in the list:
// you can use this instead of the new Array() syntax:
var table = ["Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir"];
var select = '<select id="list1" size="6">';
for (var i=0; i<table.length; i++) {
select += '<option value="' + table[i] + '">' + table[i] + '</option>';
}
select += '</select>';
document.write(select); //you should probably not use document.write though...
Usually it is better not to use document.write though. Instead, you should try selecting the element you want to append to, and then add the text to that.
HTML:
<select id="list1" size="6"></select>
JS:
function list() {
var i,
table = ["Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir"],
select = document.getElementById('list1'),
out;
for (i = 0; i < table.length; ++i) {
out += "<option value='" + table[i] + "'>" + table[i] + "</option>";
}
select.innerHTML = out;
}
FIDDLE:
http://jsfiddle.net/Z9XKp/
you can loop over the array and make your string rather than writing same code again and again .
var list="";
for(i=0;i<table.length;i++){
var val=table[i];
list+="<option value='"+val+"'>"+val+"</option";
}

How do I make a loop advance using onclick?

I've been trying to figure this out for a while, and I'm totally stumped.
I'm writing a program that is supposed to display a basic series of multiple-choice questions. You see a question, you click one of the answers, and you move on to the next question.
The problem is, I can't figure out how to display one question, then display the next question when the user clicks one of the buttons. Nothing happens when I click a button. What's going wrong?
// progress meter
var progress = new Array();
for (var i = 0; i < questions.length; i++) progress.push("0");
var i = 0;
display(0);
// display questions
function display(i) {
var prg_string;
for (var j = 0; j < progress.length; j++) prg_string += progress[j];
document.write(
"<div id = 'background'>"
+ "<div id = 'progress'>" + progress + "</div>"
+ "<div id = 'title'>-JogNog Test v1-<br></br>" + tower + "</div>"
+ "<div id = 'question'>" + questions[i].text + "</div>"
+ "<div id = 'stats'>Level " + level + "/" + total_levels + " Question " + (i + 1) + "/" + questions.length + "</div>"
+ "</div>"
);
document.write("<button id = 'answer1' onclick = 'next(questions[i].answers[0].correct)'>" + questions[i].answers[0].text + "</button>");
if (questions[i].answers.length > 0)
document.write("<button id = 'answer2' onclick = 'next(questions[i].answers[1].correct)'>" + questions[i].answers[1].text + "</button>");
if (questions[i].answers.length > 1)
document.write("<button id = 'answer3' onclick = 'next(questions[i].answers[2].correct)'>" + questions[i].answers[2].text + "</button>");
if (questions[i].answers.length > 2)
document.write("<button id = 'answer4' onclick = 'next(questions[i].answers[3].correct)'>" + questions[i].answers[3].text + "</button>");
}
// go to next question, marking whether answer was right or wrong
function next(correct) {
if(correct) progress[i] = "T";
else progress[i] = "F";
i += 1;
display(i);
}
I haven't read through your code, (you might want to work on posting SSCCEs by focusing just on the part that handles the loop) but I get the feeling a loop is not what you want here. Loops are great if you need to automatically iterate through something. But really, you want to display only a single question at a time.
The easiest way to do this, assuming you have a means of handling each question independently, is just to keep track of which question the user is up to. Display that question. When the user submits an answer, call whatever function renders a question using the counter, plus one. Make sure to check that you haven't hit the end of the quiz so that you don't reference a question that doesn't exist.
Here's some pseudocode:
var questionNumber, questions; //assume these already have values
function printQuestion(questionNumber){ ... }
function nextQuestion(){
if(questionNumber < questions){
questionNumber++;
printQuestion(questionNumber);
}
else{
showResults();
}
}
I agree with #ngmiceli that a loop isn't what you want here. You want to display one question, and then create click event handlers that will move on to the next question when the user selects an answer to the previous question.
I went ahead and created a different setup to demonstrate. You can see a demo here:
-- jsFiddle DEMO --
But I'll walk through the process. First, I set up a basic HTML document:
<body>
<h1>-Test v1-</h1>
<h2>Simple Math</h2>
<div id="container">
<div><span id="numRight">0</span> of <span id="numQuestions">0</span></div>
<div id="question"></div>
<div id="answers"></div>
</div>
</body>
Then, I created a questions array, each element in the array being an object. Each question object contains the question itself, an array of possible answers, and an "answerIdx" property that indicates the array index of the correct answer.
questions = [
{
question: 'What is 0 / 6 ?',
options: ['0','1','2'],
answerIdx: 0
},
{
question: 'What is 2 + 2 ?',
options: ['72','4','3.5'],
answerIdx: 1
}
]
I also created some other variables that point to the HTML elements I am going to want to manipulate:
numRight = 0,
numQuestions = 0,
answerDiv = document.getElementById('answers'),
questionDiv = document.getElementById('question'),
numRightSpan = document.getElementById('numRight'),
numQuestionsSpan = document.getElementById('numQuestions');
Next, I created a 'displayQuestion' function which takes a single question object as a parameter:
function displayQuestion(q) {
// insert the question text into the appropriate HTML element
questionDiv.innerHTML = q.question;
// remove any pre-existing answer buttons
answerDiv.innerHTML = '';
// for each option in the 'options' array, create a button
// attach an 'onclick' event handler that will update
// the question counts and display the next question in the array
for(i = 0; i < q.options.length; i++) {
btn = document.createElement('button');
btn.innerHTML = q.options[i];
btn.setAttribute('id',i);
// event handler for each answer button
btn.onclick = function() {
var id = parseInt(this.getAttribute('id'),10);
numQuestionsSpan.innerHTML = ++numQuestions;
// if this is the right answer, increment numRight
if(id === q.answerIdx) {
numRightSpan.innerHTML = ++numRight;
}
// if there is another question to be asked, run the function again
// otherwise, complete the test however you see fit
if(questions.length) {
displayQuestion(questions.shift());
} else {
alert('Done! You got '+numRight+' of '+numQuestions+' right!');
}
}
answerDiv.appendChild(btn);
}
}
Finally, I displayed the first question:
displayQuestion(questions.shift());

Categories

Resources