Attempting to make nested questions appear dynamically... C# ASP.Net Database First, - javascript

Idea for making elements visible or invisible:
So… how the loop works right now is it for each category, it loops through each question in each category.
The idea is: Each question can be answered yes or no, and then for each question answered yes, there can be up to 5 dates added.
What I want to do:
-If yes, first date appears:
-If the first date is answered, then a second question appears, and so on.
These questions are stored in a sql server like so:
I want only the inner loop to have this ability to be visible or invisible..
My thought is to do a nested loop and check check on each element.
//Psuedo code
//For each first question which has 5 sub questions that are all set to hidden:
var questioncount = (count of the first questions)
for(int i = 0; i<questioncount; i++){
// set first variable to hold the first questions object.
var element(‘#questionElement’ + i);
// set firstElement to selected answer
var isAnsweredYes = firstElement.(‘Yes’);
for int j = 0; i<subQuestionCount; j++)
if (isAnsweredYes == True){
// jQuery selector to get an element
var query = $('#element' + j);
// check if element is Visible
var isVisible = query.is(':visible');
if (isVisible === true) {
// element is Visible
// do nothing
} else {
// element is Hidden
query.show();
}
else
{
//do nothing
}
}
}
Does my logic seem forward? or can anyone advise me in a better way?

I would use a button that says "Add another date", which is displayed under the last date field as soon as at least one is visible. That way you won't have to decide on a certain number (e.g. 5) as the maximum, plus I think it's a rather intuitive way of extending a form.
On each press of the button, create new input controls; be it in javascript or server side, it makes no real difference.

Related

double conditions in if statement

as I'm not that good in coding i have a small issue in my code that i need to find a solution for it. my code bellow that i made is to transfer data from one sheet to another one based on value on a specific cell, that it's working perfectly, but for another case that i have i need to make double conditions for my if statement that they need to be both of them true so it can work, first condition it's the one that i already made, and the second one is i want to check if the cell number 12 is not empty.
for (i = 1; i < dataValues.length; i++) {
if (dataValues[i][11] === 'COMMANDE CONFIRMER' && ) {
pasteSheet.appendRow([dataValues[i][0],
dataValues[i][1],
dataValues[i][2],
dataValues[i][3],
dataValues[i][4],
dataValues[i][5],
dataValues[i][6],
dataValues[i][7],
dataValues[i][8],
dataValues[i][9],
dataValues[i][10],
dataValues[i][11]]);
var clearRow = i + 2;
copySheet.getRange('A' + clearRow + ':L' + clearRow).clearContent();
}
}
Column L is probably [i][11]
Based up what you added in the comment below I'd say that this is probably what you are after.
if (dataValues[i][11] === 'COMMANDE CONFIRMER' && dataValues[i][12]) { so then all you need is to make sure it's not empty. Or it's also possible that you not really sure what you want so let us know.

Why will my button not advance to the next question?

I am a new developer and this is my first question. I am trying to make a multiple choice quiz for an assignment. I am stuck on making the NEXT button move to the next question. I think the rest of the JS file is correct...
Right now the clickNext doesn't do anything, so I need to do the following
check if the time expired (line 39)
did the user answer the question in the allotted time (line 40)
if no, try again and the clock will start over (line 60-70)
if yes, then store the answer selected - I think this part is tripping me up and I am not sure what to use here
check if the selected answer is correct (line 50-57)
if the answer is correct, move to the next question (line 52-53)
if the answer is wrong, alert "Please try again" (line 55-56)
I have tried to return the answer, the addEventListener, putting the checkAnswer function in the clickNext function
var indexQuestion = 0; // Current index of question we are on
var timer = 0; // A clock that goes up by 1 every second
var timeLastSubmit = 0; // the time we last submitted an answer
var timeExpired = false; // Did time expire for current question?
// number of seconds to wait for each question
var WAIT_TIME = 30;
// all questions to be used on the website
var QUESTIONS = [
{
"question":"Which city is the capital of Ontario?",
"choices":["New York","Toronto","Berlin","Kuala Lumpur"],
"answer":1
},
{
"question":"Which city is the capital of Canada?",
"choices":["New York","Toronto","Ottawa","Vancouver"],
"answer":2
},
{
"question":"Which continent does the south pole reside?",
"choices":["Africa","Antarctica","Asia","Australia","Europe","North America","South America"],
"answer":1
},
];
function loadApplication() {
loadQuestion(indexQuestion); // load the first question into the web page
// update the timer every second and check if question has been answered yet
setInterval(function(){
timer++;
checkExpirationTime();
},1000);
}
function clickNext() {
// make sure that the user has answered the question before the time has expired
timeLastSubmit = timer;
checkExpirationTime();
// Get the answer from drop down
var selectedIndexAnswer = getElementById('choices');
return selectedIndexAnswer;
// Get the anwer from the array
var answer = QUESTIONS[indexQuestion].choices[i];
checkAnswer();
};
function checkAnswer(){
// Compare answer. Only if correct, do you move onto next question - if(answer == QUESTIONS[indexQuestion].answer)
if(selectedIndexAnswer == answer) {
nextQuestion();
}
else {
alert('Please try again.');
}
}
function checkExpirationTime() {
// check the time, once the clock has reached 30 seconds do not move to the next quesiton
if(timer - timeLastSubmit < WAIT_TIME && !timeExpired){
document.getElementById("seconds").innerHTML = WAIT_TIME;
}
else{
timeExpired = true;
alert('Please try again.');
clearInterval(timeExpired);
}
}
function nextQuestion() {
// advance to the next question, until the there are no more questions
if(indexQuestion<QUESTIONS.length-1)
{
indexQuestion++;
loadQuestion(indexQuestion);
}
}
function loadQuestion(indexQuestion){
// grab the question
document.getElementById("question").textContent = QUESTIONS[indexQuestion].question;
// build the html string for select menu
var choices = "";
var i=0;
//loop through the choices
while(i<QUESTIONS[indexQuestion].choices.length){
// create a string of <option>answer</option><option>answer</option><option>answer</option>... and load it into the choices variable
choices += "<option>" + QUESTIONS[indexQuestion].choices[i] +"</option>";
i++;
}
document.getElementById("choices").innerHTML = choices;
}
// When the DOM is ready, run the function loadApplication();
document.addEventListener("DOMContentLoaded",loadApplication);
Right now the program does not advance to the next question, but it just stays on the first question.
To answer your first question
I am stuck on making the NEXT button move to the next question
For this you need to add click event listener to next button.
document.getElementById("btnNext").addEventListener("click",clickNext)
And the next part
I think the rest of the JS file is correct.
Almost.. You need to make a few corrections here and there.
I made some edits to the pen and is available here.
https://codepen.io/nithinthampi/pen/Yzzqqae
As, you are a learner, I would suggest not to copy it. Even the codepen I shared is not complete, but should help you to move on.
Going through your pens, here are the following issues I found with your code:
Misuse of return statements. You added a return statement in the second line of your function causing the rest of it to be completely ignored.
function clickNext() {
// make sure that the user has answered the question before the time has expired
timeLastSubmit = timer;
checkExpirationTime();
// Get the answer from drop down
var selectedIndexAnswer = getElementById('choices');
Here --> return selectedIndexAnswer;
// Get the anwer from the array
var answer = QUESTIONS[indexQuestion].choices[i];
checkAnswer();
}
onclick not added to your "Next" button, neither a addEventListener in your script was. As a result, clicking the "Next" button had no effect on your app, at all.
<button id="btnNext">Next</button>
Scoping problems. In JavaScript, when you define a variable within a scope, that variable can never be accessed from outside that very scope. Meaning defining a variable inside a function (like in your case) will not make it available in another completely separate function (unless you pass it as a parameter in some way). I'd recommend researching a bit more about JavaScript scopes to get a better of idea of how it works.
All 3 issues have been fixed in a new pen I've created for you to take a look at: https://codepen.io/MMortaga/pen/PooNNYE?editors=1010
However you might need to play a bit more with your timer, so see if you can fix it :P
Take the time to review all the changes I've mentioned and if you still face any issues just comment below, I'd be glad to help.

JavaScript logic - Parsing a textarea

I need to take a textbox that is full of formatted info about accounts and then sort it somehow. I would like to know if it would be ideal (I'm trying to make this as efficient as possible) to parse the info into a two dimensional array, or if I should make account objects that will hold info in fields.
The program is simply meant to format the data so that it can be printed out without having to copy/paste.
So far I have...
function generateOutputfvoc()
{
var accountLines = document.getElementById('accountLines').value;
var accountLinesTemp = accountLines.split(/[\s]/);
for(var i = 0; i < accountLinesTemp.length; i++)
{
if(accountLinesTemp[i].match(/
Edit (1-18-13): Here is an example input. It is basically text copied from a web CRM tool. Note, this example input is something I typed up randomly.
P8B000001234567 stackoverflow Thing 12522225555 444 Active 2005-02-26 CO1000123456
P8B000001234568 stackoverflow Another Thing 444 Active 2005-02-26 CO1000123456
P8B000001234569 stackoverflow Another Thing 556 Active 2005-02-26 CO1000123456
I would like my program to take the text and simply output the text like this:
P8B000001234567 stackoverflow Thing 12522225555 444 Active 2005-02-26 CO1000123456
P8B000001234568 stackoverflow Another Thing 444 Active 2005-02-26 CO1000123456
P8B000001234569 stackoverflow Another Thing 556 Active 2005-02-26 CO1000123456
Also, I would like to know if I should use jQuery variables. I asked this because I have been looking online a lot and I found examples that use code that looks like this:
$check=fcompcheck();
if($check)
{
$output=document.frm1.type.value+" / ";
$output=$output+"Something - "+document.frm1.disco.value+" / ";
Note the: $output variable. The dollar sign indicates a jQuery variable, right?
Thank you for any help you might be able to offer me.
Update (1-19-13): I've taken a shot at it, but I'm making slow progress. I'm used to programming Java and my JavaScript looks too similar, I can tell I'm makings errors.
I'm taking it one step at a time. Here is the logic I'm using now.
Person pastes text into text box and pushes the generate button
Program takes the contents of the text box and parses it into a large array, removing only whitespace
Program then searches for patterns in the text and begins passing values into variables
I am trying to get the program to simply identify the pattern "Summary section collapse Name" because these four words should always be in this sequence. Once it identifies this it will pass the next two array values into first and last name variables. Here's some of the code:
var contactNameFirst, contactNameLast;
// Parse the input box into an array
var inputArr = document.getElementById('inputBox').value.split(/[\s]/);
for(var i = 0; i < inputArr.length; i++)
{
if(inputArr[i] == "Summary" && inputArr[i - 1] == "section" && inputArr[i - 2] == "Collapse" && inputArr[i + 1] == "Name")
{
if(inputArr[i + 2] != "Details")
{
contactNameFirst = inputArr[i + 2];
}
else
{
contactNameFirst = "";
}
if(inputArr[i + 3] != "Details")
{
contactNameLast = inputArr[i + 3];
}
else
{
contactNameLast = "";
}
}
}
document.getElementById('contactNameOutput').innerHTML = contactNameFirst + " " + contactNameLast;
Also, should I create a new post for this now, or keep editing this one?
Your accountLinesTemp is an Array of String, you could use the Array.sort function to sort your array as expected, and then use Array.join to get the full String if necessary.
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort on MDN for more information.

Peculiar behaviour with jQuery/Javascript .toggleClass/.classList.toggle

First time I ask something here, I hope you people will be as helpful as ever.
I am making a script in Javascript(using some jQuery as well) that's supposed to do this:
Suppose we have a page with user posts. If someone clicks on a user's name, on one of the posts, the script will highlight every other post of the same user.
If the posts of a user are already highlighted, and we click on another user's name, in another post, then all the previously highlighted posts must return to normal state, and now the posts of the other user must be highlighted instead.
The script I have written is this.
$(function (){
$(".showall").click(function() {
var identifier = this.innerHTML;
var already = document.getElementsByClassName("highlight");
var l = already.length;
if (l) {
for (i=0; i<l; i++) {
var to_hide = already[i].id;
$("#"+to_hide).toggleClass("highlight");
}
}
var sum = document.getElementsByClassName("uid_"+identifier)
var l = sum.length;
for (i=0; i<l; i++) {
var to_show = sum[i].parentNode.parentNode.parentNode.id;
$("#"+to_show).toggleClass("highlight");
}
});
});
Let me explain a little what it does.
When the click event is triggered on one of the specified elements, it stores the user identifier, and then checks to see if there are already highlighted comments, by checking the document for the "highlight" class.
If there are highlighted comments, it's SUPPOSED TO remove the highlight class, from each and every one of them, and then, based on the user identifier, to highlight any other posts accordingly.
The problem with the script occurs in the loop inside the if(l) {} conditional, here
if (l) {
for (i=0; i<l; i++) {
var to_hide = already[i].id;
$("#"+to_hide).toggleClass("highlight");
}
}
When removing the highlight class, it does so by skipping every other post, and only does the loop for half the length.
For example, say I highlighted a user's posts. That user had 14 posts, so, all 14 of them get highlighted. Now, if I want to highlight the posts of another user, and click on his name, the script will remove the highlight from the previous posts like this:
Remove highlight from post No1
Remove highlight from post No3
Remove highlight from post No5
Remove highlight from post No7
Remove highlight from post No9
Remove highlight from post No11
Remove highlight from post No13
When I will click on another username again, it will
Remove highlight from post No2
Remove highlight from post No6
Remove highlight from post No10
Remove highlight from post No14
etc.
I do not understand why the loop behaves that way.
I have removed the line with the .toggleClass and made it so that it alerts for every element of the array, and it did so for the whole length, not half the length, without skipping elements.
It's like when I use the .toggleClass the i gets incremented by 2, and I, for the love of me, cannot understand why. I have also tried to do it with .classList.toggle, without using jQuery, and it's the same thing again.
Any help will be much appreciated.
Regards to you all.
EDIT: Forgot to add, that Chrome's console gives me this error, for the posts that the script is skipping:
Uncaught TypeError: Cannot read property 'id' of undefined.
I understand what it means, it's like it did not find a valid object to read the id property, but I do not understand why it happens.
Your code seems overly complex.
Would something like this work for your use case?
$('.user-name').click(function (e) {
e.preventDefault();
var user_id = $(this).parent().data('userid');
if (!$(this).parent().hasClass('selected')) {
$('.post.selected').removeClass('selected');
$('.post[data-userId='+ user_id +']').addClass('selected');
} else {
$('.post.selected').removeClass('selected');
}
});

How can I ensure that changes to a form DOM are complete before POSTing?

Currently I have a race condition existing in my JavaScript code. What I am trying to do with this code is convert all check boxes which are a part of the 'checkbox' class and are not checked into text boxes with a value of zero. Currently when you post a check box that is not checked it does not appear in the $_POST data. However I need to know all the values whether true or false for these particular set of check boxes.
The code I have is here:
Code:
function checkboxConvert() {
var chkBxs = $$('.checkbox');
for (var i = 0; i < chkBxs.length; i++) {
if (chkBxs[i].checked == false) {
chkBxs[i].type = 'textbox';
chkBxs[i].value = '0';
}
}
setTimeout("document.productForm.submit();",1000);
}
Now the problem that I have been getting is that when I try to submit this form the values of the recently changed text boxes does not appear in the $_POST data. Therefore, as you can see above I have postponed the page submit for 1 sec and then I have all the data available to me. However as time goes on and my data set gets larger, 1 sec may no longer be enough. This I think is a race condition and I need to figure some way of running the code only after all the check boxes have been converted and they have their new values. I would have thought that this would be unnecessary from the start, but for some reason it's trying to run both pieces simultaneously and I can't submit until I have the proper values in place.
Any help is much appreciated!
This is definitely not the way to do web. I strongly advise you abandon your checkboxConvert function, and solve this issue on the server side
JavaScript always runs single-threaded in the browser so I don't think it can be a race condition.
I'd generally agree with others that you shouldn't do this, but your problem may be that you're changing the element to a type of "textbox" instead of "text". If you declare an input of type "textbox" in HTML markup, it will usually render as a text field anyway because that's the default. However, changing an already valid "checkbox" type input to the invalid "textbox" may not work predictably.
Try changing it to this:
function checkboxConvert() {
var chkBxs = $$('.checkbox');
for (var i = 0; i < chkBxs.length; i++) {
if (chkBxs[i].checked == false) {
chkBxs[i].type = 'text';
chkBxs[i].value = '0';
}
}
// Because JS in the browser is single-threaded, this
// cannot execute before the preceding loop completes anyway.
document.productForm.submit();
}
There's got to be a better way to do this. Try something like:
Know about all your possible values on the server side. It looks like you're using PHP; keep a simple array with the names of your checkboxes.
When you take your $_POST data, remove the names of checkboxes you've received values for from your array.
The remaining are all false.

Categories

Resources