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);
}
Related
I am trying to write a script that will document.write the variable information from an array (out of a form) but a) without the variable name = (figured that part out, see below) and b) instead put individualized text in front of each value (e.g. You pledged $ (value they entered), Your name is (value they entered) etc. It is the b) part that has me bashing my head against a wall. With just the values printing it is a lot better than "myfunkyvariablename=value" but just having the value coming out doesn't tell the person who entered the data all the information that they need. Is there a way to do this?
<script type="text/javascript">
/* <![CDATA[ */
var formData = location.search;
formData = formData.substring(1, formData.length);
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
formData = unescape(formData);
var formArray = formData.split("&");
for (var i=0; i < formArray.length; ++i) {
var printBegin=formArray[i].search("=") +1
document.write(formArray[i].substring(printBegin) + "<br />");
}
/* ]]> */
</script>
Any help on this would be seriously appreciated.
Ok, I found a solution but it will only work if you know all the elements in the form. The code above works great to strip off the unwanted variable names from the form array. What you do next is to create a second array with corresponding elements to the form elements and with values that say what you want to output. Then you put the two arrays into a table like this:
document.write("<table>")
var formData = location.search;
formData = formData.substring(1, formData.length);
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
formData = unescape(formData);
var formArray = formData.split("&");
for (var i=0; i < formArray.length; ++i) {
var printBegin=formArray[i].search("=") +1;
document.write("<tr><td>" + responseArray[i] + "</td><td>" + formArray[i].substring(printBegin) + "</td></tr>");
}
document.write("</table>");
I've got an array like this
pages['name'] = "Home";
pages['childs'][0]['name'] = "Sub page 1";
pages['childs'][1]['name'] = "Sub page 2";
pages['childs'][2]['name'] = "Sub page 3";
pages['childs'][2]['childs'][0]['name'] = "Sub sub page 1";
My problem is that I need to change portions of the array for example.
pages['childs'][0] = otherarray;
// or
pages['childs'][2]['childs'][0] = otherarray;
Obviously if otherarray was a string I can easily do something like
eval('pages' + where + ' = "' + stringvalue + '"');
But I've an array as value so I can't do
eval('pages' + where + ' = "' + otherarray + '"');
because the code executed will be
pages['childs'][0] = [object object];
What's the solution? Thanks
Rather than screw around with eval and stringifying things, you should just build an accessor. Many would agree that using eval like this is just bad practice in every way. I don't know if combining it with stringify makes it worse, but it certainly feels dirty.
Here's a basic, fairly stupid accessor, but it should give you the idea.
// Arguments: array to modify; new value; series of nested array keys.
function modifyArray(base, value){
var refObj = base;
for (var ii=2, max=arguments.length; ii < max; ii++){
if (!refObj) {
return false; // we supplied an invalid key.
}
if (ii == max-1){
refObj[arguments[ii]] = value;
return true;
}
refObj = refObj[arguments[ii]];
}
return false; // probably forgot to include keys.
}
modifyArray(pages, otherarray, 'childs', 2, 'childs', 0);
http://jsfiddle.net/2ts78brg/
For me this solution works
eval("pages" + where + " = JSON.parse('" + JSON.stringify(otherarray) + "')");
It sounds more like a workaround then a solution but it works and for me it's enough.
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;
}
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\" />";
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.