document.getElementById() is always returning null - javascript

I'm trying to get the value of a hidden input from a form in my HTML, using javascript.
But after trying several different ways to get the value, it always says in console(firebug) that the variable is null.. heres the javascript:
var mcq_test = form.mcq_test.value;
console.log("mcqid=" + mcq_test)
var mcq_num_questions = form.mcq_num_questions.value;
console.log("totalquestions=" + mcq_num_questions)
var x = 1;
var send = [];
send.push("mcq_test=");
send.push(mcq_test);
console.log("Send: " + send);
// have commented out the bits below...just go through them carefully looking at the string functions, put them in the send += (SRING 1 + STRING 2 + ...) format
for (var x = 1; x <= mcq_num_questions; x++) {
var questionidd = "mcq_question_id";
console.log("1 = " + questionidd);
var questionid = questionidd.concat(x); // mcq_question_id$ctr the question numer
console.log("2 = " + questionid);
var mcqid = form.questionid.value; // the questions id on db
console.log("3 = " + mcqid);
var answerr = "mcq_question";
var answer = answerr.concat(x); // mcq_question$ctr the questions chosen answer
var chosenanswer = form.answer.value; // the answers value
console.log("4 = " + chosenanswer);
var amp = "&";
var equal = "=";
var questionide = questionid.concat(equal); // "mcq_question_id$ctr="
var questionida = amp.concat(questionide); // "&mcq_question_id$ctr="
var answere = amp.concat(answer,equal); // "&mcq_question$ctr="
if (x = 1) { send.push(questionide, mcqid, answere, chosenanswer); }
else {
send.push(questionida, mcqid, answere, chosenanswer);
}
}
Console:
[04:08:00.328] TypeError: questionID is null
[04:08:00.327] My new function
[04:08:00.327] mcqid=566
[04:08:00.327] totalquestions=3
[04:08:00.327] Send: mcq_test=,566
[04:08:00.328] 1 = mcq_question_id
[04:08:00.328] 2 = mcq_question_id1
Form:
echo"<input type=\"hidden\" name=\"mcq_question_id$ctr\" id=\"mcq_question_id$ctr\" value=\"$questionID\" form=\"SubmitTest\" />";
-- Update
Answer found! Turns out, you can't use the syntax document.getElementByID() or form.variable.value; and put a variable in there, it has to be a string or written like this:
form[variable].value;
I didn't find an equivalent for getElementById but the form method works for me.

You need to make sure that the DOM has loaded before you try accessing it. Put the Javascript after the HTML or setup an event to trigger the variable definition.

when using this
echo"<input type=\"hidden\" name=\"mcq_question_id$ctr\" id=\"mcq_question_id$ctr\" value=\"$questionID\" form=\"SubmitTest\" />";
here before going to create input type make sure your '$questionID' is not null
use this then test
echo"<input type=\"hidden\" name=\"mcq_question_id$ctr\" id=\"mcq_question_id$ctr\" value=\"questions\" form=\"SubmitTest\" />";

Related

Add JSON object to Dictionary Value

Hi i'm currently trying to do a function that will get a key(string)/value(JSON) pair from a dictionary stored at a database and add information about the player into a temporary JSON(playersInfo), then set that JSON object back to the value which i got earlier, i'm still very noob at javascript and i couldn't find the right syntax to do it.
If there's anything i can do to make myself clear please let me know.
Both Get...Data() functions return different dictionaries.
handlers.UpdateJackpotPlayers = function(args, context) {
var playersInfo = {};
var userData = server.GetUserData({
PlayFabId: currentPlayerId
});
var serverData = server.GetTitleInternalData();
playersInfo = JSON.parse(serverData.Data["jackpotPlayers"].Value);
playersInfo.PlayerId += JSON.parse(" / " + currentPlayerId);
playersInfo.PlayerName += JSON.parse(" / " +
userData.Data["PlayerName"].Value);
playersInfo.AchievedJackpot += JSON.parse(" / " + args);
server.SetTitleInternalData({
"Key": "jackpotPlayers",
"Value": JSON.stringify(playersInfo)
});
}

Performing calculations on data via json

I am trying to perform a simple addition on data I have gathered from an external source via JSON. The data I am getting is being returned as a string but is a number so I have tried using both parseInt() and Number() to no avail. I have shown a simple section of the code below:
var total_energy = 0;
var energy_val;
$.each(result.report.food.nutrients, function (i, v) {
if (v.name == "Energy"){
energy_val = v.value;
var energy = Number(energy_val);
total_energy = total_energy + energy;
console.log("energy " + energy);
console.log("totalenergy " + total_energy);
energy_val = "";
energy = 0;
}
}
The console returns the correct value for energy each time but the totalenergy value just seems to stay the same as the energy value. The sum doesn't seem to have any affect. Could anyone tell me where I am going wrong with this problem?
change console.log("energy " + total_energy); to console.log("energy " + energy);
try parseInt your values... can be this
I doubt if its due to the closure created in the loop where you are iterating over the items. Try the following code.
var total_energy = 0;
var energy_val;
$.each(result.report.food.nutrients, function (i, v) {
var item = v;
//Calling calculateEnergy() function so that each 'item' is the current instance 'v' value.
(function calculateEnergy(itemClicked))(item);
}
function calculateEnergy(itemClicked){
if(itemClicked.name == "Energy"){
energy_val = itemClicked.value;
var energy = Number(energy_val);
total_energy = total_energy + energy;
console.log("energy " + energy);
console.log("totalenergy " + total_energy);
energy_val = "";
energy = 0;
}
}
I have put comments within the code.
Update console.log() is buggy with ajax requests. So instead of logging, try creating an html div and populate the values there.

Using data attributes in JavaScript

I am trying to use the data attribute to change the page to details about the selected product in my index web page.
These are the functions that I am using at the moment. This works but it will only display the innerHTML of the document. Whereas i want all of the data about the object that is stored in a data attribute called data-detail. The responseText would be something similar to this:
data-detail='{"ID":"1", "Name":"Some Name", "Description":"Some Description", "Price":"100", "Photo":"SomePath/AnotherPath/Image.png"}'
function displayItems(results){
article = document.getElementById("homeSection");
string = '<h1>Company Name</h1><h2>Why not try these products?</h2>';
for(var i=0; i<results.length; i++){
var price = parseFloat(results[i].Price);
var sec = document.createElement("section");
sec.classList.add("homeItem");
sec.dataset.detail = JSON.stringify(results[i]);
article.appendChild(sec);
sec.innerHTML = '<div class="imageContainer"><img class="resultsImage" src="' + results[i].Photo + '"></div><p class="resultsName">' + results[i].Name + '</p><p class="resultsPrice">£' + price.toFixed(2) + '</p>';
var items = document.querySelectorAll(".homeItem");
for(i=0; i<items.length; i++){
items[i].addEventListener("click", selectedProduct);
}
}
}
function selectedProduct(event){
target = event.currentTarget;
homeSection = document.getElementById("homeSection");
console.log(target.detail.ID);
homeSection.innerHTML = target.innerHTML;
}
After clicking on an element, the console is telling me that data.detail is undefined after parsing through the 3rd line down in the selectedProduct function. I wonder if anyone could tell me why this is and if I am being silly and not spotting the problem.
As you can store only string values, So after getting the value, you need to convert back to object by calling JSON.parse(). You also need to use dataset to get the value as you are setting the value.
function selectedProduct(event){
target = event.currentTarget;
homeSection = document.getElementById("homeSection");
console.log(JSON.parse(target.dataset.detail).ID);
homeSection.innerHTML = target.innerHTML;
}

How to change form display from = to :?

is there anyway that I can change the output from
Name: =daniel to Name: Daniel for all of the followings?
Picture in this URL > http://imgur.com/dgOMjhy
<h2>Your details have been submitted!</h2>
<h2>You have entered the following data: </h2>
<script type="text/javascript">
var formData = location.search;
formData = formData.substring(1, formData.length);
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
formData = unescape(formData);
var formArray = formData.split("&");
document.write("<p>");
for (var i = 0; i < formArray.length; ++i) {
document.writeln(formArray[i] + "<br />");
}
document.write("</p>");
</script>
Sure, but this won't get you very far.
Change this line:
document.writeln(formArray[i] + "<br />");
to
document.writeln(formArray[i].replace("=", ": ") + "<br />");
But if I were you I would work on parsing the data into an actually usable object for further manipulation, currently you only work by doing String manipulations on the page URL.
Edit: To expand on the question you posted in the comment to this post:
To begin, you should try to move away from moving data via URL or GET requests, as these are quite visible, restrictive in encoding, prone to manipulation and recording. Especially data like credit card information should not be embedded in URLs.
Anyhow, in regard to parsing let's start with splitting your formArray further and storing the key-value pairs in an object:
var formArray = formData.split("&");
var formDataObj = {}; //in this we will store the data
//let's assume here that you have no key duplicates in your data
//and that it is always properly formatted
formArray.forEach(function (item) {
var key = item.split("=")[0];
var value = item.split("=")[1];
formDataObj[key] = value;
});
//if you processed your data like this you can then access it more precisely like so
document.writeln("<p>Customer " + formDataObj.customerNumber + " has card number " + formDataObj.cardNumber + "</p>");
I think it's obvious how this can be advantageous.
you can use a helper function
function capitalize(a)
{
return a[0].toUpperCase() + a.slice(1);
}

using localStorage to keep a count

var nicWinsVsMac;
if (tempresult === win) {
wincount = JSON.parse(localStorage.getItem (playerName + 'wincount'));
wincount += 1;
localStorage.setItem(playerName + 'wincount', wincount);
winsvsopponent = 'WinsVs' + opponent;
winsvsopponent = JSON.parse(localStorage.getItem(playerName + 'WinsVs' + opponent));
winsvsopponent += 1;
console.log(winsvsopponent);
localStorage.setItem(playerName + 'WinsVs' + opponent, 'winsVs' + opponent);
console.log(localStorage.getItem(nicWinsVsMac));
}
playerName and opponent are parameters passed in. In this case, playerName = 'nic' and opponent = "Mac"
My browser is giving me "unexpected token w" on the line where i parse out the localStorage. I cannot figure out what is going on. Any help would be great. Thanks!
Instead of using a separate localStorage variable for each attribute of the player. Why not store all the players attributes in a single object and then save that to localStorage.
For example, you can do the following:
var player = new Object();
player.name = 'Mac';
player.winCount = 3;
player.winAgainst = new Array();
localStorage.setItem(player.name, JSON.stringify(player));
var player1 = JSON.parse(localStorage.getItem(player.name));
console.log(player1.name + " has " + player1.winCount + " wins.");
This allows you to save all the player's attributes to a single localStorage variable making it much easier to read and write from.
In regards to the error you are recieving, I believe the issue with your code is that you are not using JSON.stringify in the call to setItem.

Categories

Resources