I need to know how to get the h1 sun emoji to change when user input less than or equal to 0.
I feel like I have the logic but just need to code.
Once the user inputs a temperature less than 0 the h1 needs to change to a certain emoji or content.
Can I get some advice please. I am struggling here. this is my code:
function question() {
let city = prompt("what city do you live in?");
let temp = prompt("What temperature is it?");
let h1 = document.queryselector("h1");
h1.innerHtml = "Currently" + temp + "degrees" + " in " + city;
}
function change() {
switch (true) {
case (temp <= 0):
document.getElementById("h1").innerHtml = "Currently" + temp + "degrees" + "in " + city;
}
}
<h1>
sun emoji
</h1>
<h1 class="temperature">
Currently 21 degrees in Tokyo
</h1>
<h2>
13 degrees / <strong>23 degrees</strong>
</h2>
The h1 has to change to a different emoji based on the users response of less than or equal to 0.
Along with the emoji I need to input of the user city to change along with it.I just need the h1 section to change.Should I use a switch or if else statement?
Firstly, you have multiple h1 elements - queryselector only returns the first one, so in this case you would be replacing the emoji, not the text.
It would be prudent to give the various elements that you intend to edit id fields.
<h1 id="emoji-el">
sun emoji
</h1>
<h1 id="temp-details" class="temperature">
Currently 21 degrees in Tokyo
</h1>
Now you can use queryselector to select the correct elements.
Secondly, I'd like to say that it is good practice to have every function have a single responsibility - for example, one function get a correct emoji, while another puts things into elements.
Given this, I would use an if list because of the way your condition is structured:
function getEmoji(temp) {
if (temp < 0) return ❄️;
if (temp < 13) return ☁;
return ☀️;
}
You can likely use emojis directly for HTML text values, and if you only use upper limits like I did you don't need elses. IMO this is the nicest way.
You final function would look something like this:
function questionUser() {
const city = prompt("What city do you live in?");
const temp = prompt("What temperature is it?");
updatePage(temp, city);
}
function updatePage(temp, city) {
const emojiElement = document.queryselector("#emoji-el");
const tempElement = document.queryselector("#temp-details");
const emoji = getEmoji(Number(temp));
emojiElement.innerHtml = emoji;
tempElement.innerHtml = `Currently ${temp} degrees in ${city}.`;
}
This way you would be able to re-use the update logic elsewhere, and also it is clear what every function does.
Hope this helps.
Can achieve the same result with switch or if statement.
You just have to trigger the function on onChange or onBlur.
It's advisable to use classNames or id's for your html element, which makes retrieving specific elements easier.
Switch is suitable if your conditions have a fixed value. In this case a a ternary (conditional operator) would be an idea.
Here's an exemplary snippet demoing ternary or switch to determine the 'emoji' to display, based on the given temperature. It uses event delegation for handling the button click.
document.addEventListener(`click`, handle);
function handle(evt) {
// act only if button#showTemperatures is clicked
if (evt.target.id === `showTemperatures`) {
return question();
}
}
function emo(temp) {
const emojiTxt = temp < 15 ? `*Brr**` :
temp < 25 ? `*nice*` :
temp < 30 ? `*it's getting hot here*` : `*tropical!*`;
document.querySelector(`.emoji`).textContent = emojiTxt;
}
/* using switch is possible, but you need something extra */
function emoSwitch(temp) {
const lt = n => temp < n;
let emojiTxt = ``;
switch (true) {
case lt(10):
emojiTxt = `*Brr*`;
break;
case lt(25):
emojiTxt = `*nice*`;
break;
case lt(30):
emojiTxt = `*it's getting hot here*`;
break;
default:
emojiTxt = `*tropical!*`;
}
document.querySelector(`.emoji`).textContent = emojiTxt;
}
function question() {
// id's make your coding life simple
const city = document.querySelector(`#city`).value;
const temp = document.querySelector(`#temp`).value;
// one of the values is not filled, alert
if (!city.trim() || temp < 0) {
return alert(`please fill out both fields`);
}
// fill in h1.temperature
document.querySelector(`.temperature`).textContent =
`Currently ${temp} degrees in ${city}`;
// fill in the emoji
return document.querySelector(`#switch`).checked ?
emoSwitch(temp) : emo(temp);
}
<!-- changed for demo -->
<p>
<b class="emoji"></b>
<b class="temperature">Currently 21 degrees in Tokyo</b>
</p>
<hr>
<p><input type="text" id="city"> What city do you live in?</p>
<p><input type="number" id="temp" min="0" max="55"> What temperature is it up there?</p>
<p>
<button id="showTemperatures">Fill in</button>
<input type="checkbox" id="switch">Use switch
</p>
I'm Trying to get all the classnames with "items" and checking if innerHTML of each className by for loop and with given string. But even though the condition is true, nothing is happening in if condition.
I've implemented with the javascript and everything is working except the getElementsByClassName is not working
function clearAndAdd(){
var texter = document.getElementById("textBox").value;
if (texter != ""){
var allList = [];
document.getElementById("textBox").value = "";
created = 'deleteCurrent("'+texter+'")';
document.getElementById("lister").innerHTML = document.getElementById("lister").innerHTML+"<li class='items' onclick='"+created+"'>"+texter+"<span></span></li>";
document.getElementById("textBox").focus();
}
}
function deleteCurrent(text){
var allList = [];
var list = document.getElementsByClassName("items");
for(var i=0; i<list.length; i++){
var value = list[i].innerHTML;
if (value == text){
document.getElementById("output").innerHTML = value;
break;
}
}
}
<!-- HTML code -->
<body>
<div class="input-categories">
<ul id="lister">
</ul>
<input type="text" id="textBox" onblur="clearAndAdd();" />
</div>
<div id="output">
</div>
</body>
When I'm running the code with passing the string in text... even the value and the text are same, if condition is not executed. Can anyone help me with this
The content returned by list[i].innerHTML contains a <span> tag, so obviously it will never match the text you look for.
Instead of innerHTML use the textContent property: that will just return the text content:
var value = list[i].textContent;
I have the following setup - http://codepen.io/anon/pen/WvjmLv?editors=100 and am trying to output text depending on which button is clicked
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="right-answer" type="button">6</button>
<button class="wrong-answer" type="button">10</button>
<script>
var text;
var wrongAnswer = document.getElementsByClassName("wrongAnswer").addEventListener("click");
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click");
if (wrongAnswer) {
text = "Incorrect!";
text = "Wrong!";
text = "Try Again!";
}
if (rightAnswer) {
text = "Correct!";
}
document.getElementById("answer").innerHTML = text;
</script>
</div>
<div>
<p id="answer"></p>
</div>
If the user selects the wrong answer, it should either read Wrong!, Incorrect! or Try Again! (without repeating the same text output if their next guess is also wrong)
If they get the answer right, it should just simply read Correct!
As I'm fairly new to JavaScript, I feel as though I'm a little bit off with my solution and was wanting to know how can I make this function work?
Thanks.
Easiest and fastest way to get the result you want is by adding onclick-eventhandlers to your buttons.
<button onclick="somefunction()"></button>
After that you can easily handle what should happen after that click.
In your case I would check what's in the class attribute of the button you clicked.
By doing this you can print the results to your #answer-container.
With a simple array and a global variable of which index is next you can output different "false"-messages.
var _i = 0;
var _wrongs = ['Incorrect!', 'Wrong!', 'Try Again!'];
function showResult(b) {
var res = document.getElementById('answer');
if (b.classList.contains('right-answer')) {
res.innerHTML = 'Correct'
} else {
res.innerHTML = _wrongs[_i];
_i = _i > 1 ? 0 : _i + 1;
}
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" onclick="showResult(this)">2</button>
<button class="wrongAnswer" onclick="showResult(this)">5</button>
<button class="right-answer" onclick="showResult(this)">6</button>
<button class="wrong-answer" onclick="showResult(this)">10</button>
</div>
<div>
<p id="answer"></p>
</div>
Demo on Codepen
Well, there are a couple things that you need to do:
You do not have a separate click handler function defined.
You need to properly add the event function to the addEventListener call.
You cannot attach an event to multiple elements at once. You need to loop over them.
Why do you have two different classes? i.e. 'wrongAnswer' and 'wrong-answer'? Please make sure that you stick with one convention.
I added an onReady() to wait for the DOM to load before accessing and adding listeners to the elements.
Addition Information
Below, I have wrapped the document.getElementsByClassName(className) call with [].slice.call(scope, [begin[, end]]) because the result of getElementsByClassName is a NodeList. You cannot treat a list like an array in JavaScript. Since I used Array.prototype.forEach to loop over the elements, they needed to transformed into an array. This is simply syntactic sugar in order to make the code look more aesthetically pleasing and readable.
This could have easily been accomplished with a for-loop:
var nodes = document.getElementsByClassName("rightAnswer");
for (var i = 0; i < nodes.length; i++) {
var el = nodes[i];
el.addEventListener('click', clickHandler);
}
Code
var wrongTextArr = ['Try Again!', 'Wrong!', 'Incorrect!'];
var guesses = 0;
onReady(function() {
// Set the number of guesses equal to the number of questions - 1.
guesses = document.querySelectorAll('.question button').length - 1;
[].slice.call(document.getElementsByClassName('wrongAnswer')).forEach(function(el) {
el.addEventListener('click', clickHandler);
});
[].slice.call(document.getElementsByClassName('rightAnswer')).forEach(function(el) {
el.addEventListener('click', clickHandler);
});
});
function clickHandler(e) {
var text = '';
var target = e.target;
var targetClass = target.className;
if (guesses < 1) {
text = 'You have reached the max number of attempts!';
} else if (targetClass === 'wrongAnswer') {
text = wrongTextArr[--guesses]; // Decrement guesses.
} else if (targetClass === 'rightAnswer') {
text = 'Correct!';
} else {
text = 'Unexpected Error!';
}
document.getElementById('answer').innerHTML = text;
}
function onReady(callback) {
var intervalID = window.setInterval(function() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}, 1000);
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
In the code above, I tried not to stray too far away from your original code, I just simply pointed out things that made your code not work and fix them with the minimalist amount of effort. Here is my solution that I would go with.
var wrongTextArr = ['Try Again!', 'Wrong!', 'Incorrect!'];
var guesses = 0;
onReady(function() {
// Set the number of guesses equal to the number of questions - 1.
guesses = document.querySelectorAll('.question button').length - 1;
addEventListeners('button[class$="Answer"]', 'click', function(e) {
document.getElementById('answer').innerHTML = getText(e.target.className.split());
});
});
function getText(classList) {
if (guesses < 1) {
return 'You have reached the max number of attempts!';
} else if (classList.indexOf('wrongAnswer') > -1) {
return wrongTextArr[--guesses]; // Decrement guesses.
} else if (classList.indexOf('rightAnswer') > -1) {
return 'Correct!';
} else {
return 'Unexpected Error!';
}
}
// Generic functions.
function addEventListeners(selector, event, listenerFn) {
[].slice.call(document.querySelectorAll(selector)).forEach(function(el) {
el.addEventListener(event, listenerFn);
});
}
function onReady(callback) {
var intervalID = window.setInterval(function() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}, 1000);
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
Lots of good answers.. Here is another approach,
HTML:
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">2</button>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">5</button>
<button class="rightAnswer" type="button" onclick="checkAnswer(this)">6</button>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">10</button>
</div>
<div>
<p id="answer"></p>
</div>
JS:
<script>
var count = 0;
var wrongtext = ["Incorrect!", "Wrong!", "Try Again!"];
function checkAnswer(el) {
if (el.classList.contains('wrongAnswer')) {
count++;
if(count === 3)
count = 0;
alert(wrongtext[count])
}
if (el.classList.contains('rightAnswer')) {
alert('correct');
}
}
</script>
Demo:
https://jsfiddle.net/cubq361t/22/
I am not totally sure how to make it so it will say different things like "wrong" and "incorrect" but I hope this will point you in the right direction:
<!DOCTYPE html>
<html lang="en">
<body>
<div class="section">
<p>How many sides does a hexagon have?</p>
<input type="button" onClick="wrongAnswer()" value="2">
<input type="button" onClick="wrongAnswer()" value="5">
<input type="button" onClick="rightAnswer()" value="6">
<input type="button" onClick="wrongAnswer()" value="10">
<p id="text"></p>
</div>
<script>
function wrongAnswer() {
document.getElementById('text').innerHTML = "Wrong";
}
function rightAnswer() {
document.getElementById('text').innerHTML = "Correct!";
}
</script>
</body>
</html>
Here is an updated version of your code. The main issue you had was mixing up your variable and function names.
Here is a
Fiddle
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
<script>
var text;
var wrongAnswers = document.getElementsByClassName("wrongAnswer");
var rightAnswers = document.getElementsByClassName("rightAnswer");
for (var i = 0; i < wrongAnswers.length; i++) {
// alert( wrongAnswers[i]);
wrongAnswers[i].addEventListener('click', printWrongAnswer);
}
for (var i = 0; i < rightAnswers.length; i++) {
rightAnswers[i].addEventListener('click', printRightAnswer);
}
function printRightAnswer() {
text = "Correct!";
printAnswer();
};
function printWrongAnswer() {
text = "Incorrect!";
text += "Wrong!";
text += "Try Again!";
printAnswer();
}
function printAnswer() {
document.getElementById("answer").innerHTML = text;
}
</script>
In addition to the answers of Mr. Polywhirl and Bellash:
If you are new to JavaScript you should try to understand how the EventBindings are working. Every binding in JavaScript is an event, so if you click somewhere the Browser will check if he will find a binding which is listening to the event "click". So its irrelevant when you bind the event but it has to be before the click. However you have to tell JavaScript which function he has to call if someone clicks your button! Thats because events are kinda "floating" in you browser scope, they are present but know one knows when they are actually be triggered but if they are getting triggered the script have to know what gets triggered or in other words: which functionality should be triggered now?
Your lines
var wrongAnswer = document.getElementsByClassName("wrongAnswer").addEventListener("click");
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click");
are wrong because you never told the event "click" what functionality should be executed if the button is clicked.
The call or one type of a correct call would be:
var someFunction = function() { // DO YOUR AWESOME WORK PLS! }
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click", someFunction);
and in addition to that:
I don't know how experienced you are in programming but this lines
text = "Incorrect!";
text = "Wrong!";
text = "Try Again!";
will override each other, because you are using the same variable in all 3 rows ;)
Mr. Polywhirl and Bellash posted you some good example to begin with. Try them out and try to understand them!
Hope this makes it a bit clearer!
cheers,
Sebastian
Here's a rewrite of your code, providing comments as a sort of tutorial:
Update: added random response generation.
HTML:
<div class="question">
<p>How many sides does a hexagon have?</p>
<!--
Use a common class ('answer-button' used here) for all buttons
so that clicks can be easily handled with a single listener.
Since you know any answers that aren't right are wrong, you can
simply add a 'right-answer' class for that one and leave the
others as is.
-->
<button class="answer-button" type="button">2</button>
<button class="answer-button" type="button">5</button>
<button class="answer-button right-answer" type="button">6</button>
<button class="answer-button" type="button">10</button>
</div>
<div>
<!--
Using an id is often unnecessary, so I'd switch this to a class.
Since the above buttons represent answers, using an "answer" class
on this paragraph can bring confusion, so I'd recommend using something
more accurate, such as "response".
-->
<p class="response"></p>
</div>
<!--
Generally you'll want your js in a separate file. If you include the script, whether
inline or separate, at the bottom of the body element, as you did initially, it will
automatically execute after the dom has initialized, which is good.
-->
JavaScript:
// Wrap in an immediately invoking function expression
// to keep your variables off the global scope.
(function() {
// Capture all of your response phrases in an object.
var responses = {
correct: [
"Correct!"
],
incorrect: [
"Wrong!",
"Try Again!",
"Incorrect!"
]
};
// Get the element that will display your answer.
// getElementsByClassName returns an array, so get the
// first element in the array.
var response = document.getElementsByClassName('response')[0];
// Get all of the answer buttons.
var answerButtons = document.getElementsByClassName('answer-button');
// Set a listener on each answerButton element.
for (var i = 0; i < answerButtons.length; i++) {
// Add the event listener to the element. When the event occurs,
// the checkAnswer function will run, and will be passed an event object.
answerButtons[i].addEventListener('click', checkAnswer);
}
// event is an object that is automatically passed in
// when the listener calls this function, and event.target
// is the element where the event occurred.
function checkAnswer(event) {
// initialize a variable for the message
var message;
// get the element where the event occurred
var element = event.target;
// get all classes from target element
var classes = event.target.className;
// classes will be in a space-separated string, so
// we convert that to an array
classes = classes.split(' ');
// check if a specific class is in the array
if (classes.indexOf('right-answer') >= 0) {
// if the 'right-answer' class is there, they
// clicked the right answer.
message = getRandomArrayElement(responses.correct);
} else {
// otherwise, they clicked the wrong answer
message = getRandomArrayElement(responses.incorrect);
}
// set the target element's content to the message
response.textContent = message;
}
function getRandomArrayElement(array) {
// This function picks a random element from an array and
// returns it.
// You're going to want to pick one of these array items by their
// index, so we'll set up variables to capture the lowest and
// highest possible numbers that can be used.
var min = 0;
var max = array.length - 1;
// Javascript provides random numbers using the Math.random function,
// wich gives a random float between 0 and 1. The expression below
// uses that to generate a random number within a given range - in this
// case, between min and max.
var index = Math.floor(Math.random() * (max - min + 1)) + min;
return array[index];
}
})();
I have edited your code to help you understand how you could deal with .getElementsByClassName
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="rightAnswer" type="button">10</button>
</div>
<div>
<p id="answer">ok</p>
</div>
<script>
var text="...",
wrongs=document.getElementsByClassName("wrongAnswer"),
rights=document.getElementsByClassName("rightAnswer"),
wrongTexts=["Incorrect","Try Again","Wrong!"],
i=0;
for(var i=0; i< wrongs.length; i++){
wrongs[i].addEventListener("click",function(e){
text = "Incorrect!";
DisplayText();
});
}
for(var i=0; i< rights.length; i++){
rights[i].addEventListener("click",function(e){
text = "Correct!";
DisplayText();
});
}
function DisplayText(){
i=i%wrongTexts.length;
text=text=="Correct"?text:wrongTexts[i++];
document.getElementById("answer").innerHTML = text;
}
</script>
Make a function first and the assign it to the buttons like
<button onclick="myFunction()">Click me</button>
<p class="demo"></p>
Then in the JS
function myFunction() {
document.getElementByClassName("demo").innerHTML = "Hello World";
}
in your pen make a function add all the logic in it and call it on button click
I want to have a user input a string of names of their favorite music artists, but they can only enter up to five of them, and then use this string in the array to display the user's choices.
Here is my code:
<div id="results">
<p id="resultsExpl"></p>
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
</div>
<form>
<fieldset>
<label for="plBox" id="placeLabel">
Please tell us!
</label>
<input type="text" id="placeBox" />
</fieldset>
<fieldset>
<button type="submit" id="artist">Submit</button>
</fieldset>
</form>
</article>
<script>
// new array to store entered music artists
var music = [];
// counter variable to track array indexes
var i = 0;
//function to add input to array and then generate list after 5th submission
// clear text box after submit
function processInput() {
document.getElementById("placeBox").value = ""
// add entered value to array
places[i] = document.getElementById("placeBox").value;
// write each array element to its corresponding list item
for (i = 0; i < 5; i++) {
listItem = "item" + i;
document.getElementById(listItem).innerHTML = places[i];
}
// iterate counter variable
if (i < 5) {
i++;
// add entered value to array and write results to document
} else {
listItem = "";
document.getElementById("resultsExpl");
document.write.innerHTML = "These are your favorite artists:" + listItem;
}
var submitButton = document.getElementById("artist");
document.addEventListener("click", processInput, false);
if (submitButton.addEventListener) {
submitButton.addEventListener("click", processInput, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", processInput);
}
}
</script>
In the beginning of the function, you are clearing the value before saving it in the places variable
document.getElementById("placeBox").value = ""
// add entered value to array
places[i] = document.getElementById("placeBox").value; // places[i] is just set to ""
Hence it keeps storing blank strings ("")
You are also using the same variable "i" to iterate over for loop and use as a reference to how much of places filled upto now.
EDIT 1 :
Some more issues ...
The event is not being attached to the button. This is because the code to attachEvent is inside the function "processInput", but processInput is not being called. The lines
var submitButton = document.getElementById("artist");
document.addEventListener("click", processInput, false);
if (submitButton.addEventListener) {
submitButton.addEventListener("click", processInput, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", processInput);
}
need to be outside the function.
Another problem is places is not defined in the global scope. You need to add
var places = [];
in the top - near
var music = [];
var i = 0;
EDIT 2 -- Some more errors (part 2)
The for loop over the list items goes from 0 to 4, but the ids in the html code are 1 to 5
I think there are many bugs in your code. You need to write it bit by bit and keep testing your code so that you dont ever get so many accumulated bugs. Accumulated bugs makes it very difficult to debug.
A button on my webpage stops working every few days and then starts working again without any intervention/modifying source code. This "Next" button calls a javascript function to iterate forward through an array of text already retrieved via php, but sometimes it stops working. I have not touched this code for more than a month, and during this time I have seen it working most of the time - but not always. Today it's not working.
Here is the button declaration:
<input type="button" value="Next Question" class="button" onclick="submitform('Next')" style=" padding: 0.25em 1em 0.25em 1em;" id="nextQButton"/>
The button calls function submitForm with parameter "Next."
function submitform(x)
{
document.getElementById("alertShow").innerHTML = ""
if(x=='Back')
{
....
}
else if(x=='Next')
{
alert("next Q!");
if(jj+1<numQQ){
runningSum += qnumans_array[jj];
}
++jj;
++j;
kk=0;
if (jj == limit)
{
if((viewQ==null)&&(viewA==null))
{
window.location="judge.php?counter="+j;
}
else if(viewQ)
{
window.location="judge.php?&counter="+j+"&viewQ="+viewQ;
}
else if(viewA)
{
window.location="judge.php?&counter="+j+"&viewA="+viewA;
}
}
alert("middle of next q bit1");
if( jj>=numQQ && jj!=limit)
{
--jj;
--j;
alert("middle of next q bit if statement");
document.getElementById("alertShow").innerHTML = "end of available questions for this category";
}
alert("middle of next q bit2");
alert("jj is"+jj);
alert("qid array at jj is"+qid_array[jj]);
document.getElementById('qidInput').value = qid_array[jj]; ///*****this is where it stops outputting script alerts. all alerts before this output as they should.
***********************************************
alert("middle of next q bit3");
document.getElementById('jjInput').value = j;
alert("middle of next q bit4");
document.getElementById("questionShow").innerHTML = quser_array[jj] + ": "+ question_array[jj];
alert("middle of next q bit5");
if(qnumans_array[jj]>0)
{
document.getElementById("answerShow").innerHTML = auser_array[kk + runningSum] + ": " + answer_array[kk + runningSum];
}
else
{
document.getElementById("answerShow").innerHTML = "No answers posted to this question.";
}
alert("got to end of next q bit");
}
....
}
The line after which the alerts fail relates to this input field in an html form in the same php files:
<input type = 'hidden' id = 'qidInput' name = 'qid' >
Chrome debugging tool gives me this error
Uncaught TypeError: Cannot set property 'value' of null
on every line that calls:
document.getElementById("qidInput").value = qid_array[jj];
Even though these similar calls generate no error:
document.getElementById("jjInput").value = j;
document.getElementById("kkInput").value = kk+runningSum;
All these HTML elements are declared together and are of the same type:
<form name="messageInput" id = 'idForm' method="get" action="judge.php?"
onSubmit="return validate(this)">
<center><textarea name='text' style="height: 1em"></textarea><br>
<input type = 'hidden' id = 'qidInput' name = 'qid' >
<input type = 'hidden' id = 'jjInput' name = 'counter' >
<input type = 'hidden' id = 'kkInput' name = 'kk' >
<ul class="actions">
<li><input type="submit" value="Post Message" class="button"/></li>
</ul>
</center>
</form>
If I comment out every line that contains qidInput, the error message switches to giving the same error, now for every line that contains "jjInput." So it seems to be something about the ordering - whichever HTML element is called by id first is nil.
This happens on the same computer and browser on different days. The conditions on the webpage are the same, too.
Any debugging advice would be appreciated. Thank you.
Fixes that didn't work:
-swapping single and double quotes
-adding a "dummy" element and setting it first (so it's probably not ordering)