I'm working on a webpage where i'm trying to display a question, and have viewers submit an answer, which appears on another page. Currently, only the most recent answer is shown on the answer page. I'm not sure how to write my function so that it stores and displays all responses. (I'm new to javascript) Thanks!
<div id=q2 class="question gr">
What is good design?
<input id="q2input" type="text" >
<div class="buttons"> <button onclick="functionTwo()"
class="sbuttons">Submit</button>
<!-- View Answers Button -->
<button id="ViewAnswers2" class="vabuttons" >View Answers</button>
<script type="text/javascript">
document.getElementById("ViewAnswers2").onclick = function () {
location.href = "WhatIsGoodDesign.html";
};
</script>
</div>
<script>
function functionTwo(){
var input = document.getElementById("q2input").value;
console.log(input);
localStorage.setItem("question2", input);
window.location.href = "WhatIsGoodDesign.html";
}
</script>
Use an array instead. Currently, all you are doing is overwriting the current value in the question2 answer slot every time. Arrays are ways to store multiple data values into one variable
function functionTwo() {
var input = document.getElementById("q2input").value;
var answers = JSON.parse(localStorage.getItem("question2answers")) || [];
//Not too sure about the || [];
answers.push(input);
localStorage.setItem("question2answers", JSON.stringify(answers));
window.location.href = "WhatIsGoodDesign.html";
}
You cannot directly put an array into LocalStorage, so you have to pass it in and out as a JSON object. JSON.stringify() will turn it into a string that you can pass into LocalStorage, while JSON.parse() will translate that string back into an array.
You currently overwrite the key question2 with the new answer each time. If you want a list of the the last answers. You would have to do something along the lines of:
function functionTwo(){
var input = document.getElementById("q2input").value;
var numAnswers = localStorage.getItem("question2numAnswers") || 0;
localStorage.setItem("question2answer" + numAnswers.toString(), input);
localStorage.setItem("question2numAnswers", numAnswers + 1);
window.location.href = "WhatIsGoodDesign.html";
}
This way you keep track of the number of answers with question2numAnswers and each answer with question2answer# and you can loop through the answers on your next page by going from 0 to question2numAnswers that you store.
Related
I'm learning JS and I need some help figuring out why my info isn't getting populated in the html. I'm just trying to get the basic functionality to work, so that I can continue to expand on it.
User is supposed to input a 3 digit route value, which will then return all the route information from an api call. I was able to get the route info to display earlier when I got the api call set up, but I'm struggling to figure why it's not displaying now that I tried adding in a feature to allow the user to input the route. See attached pen
HTML
<div class='container'>
<h1 id='header'>Route Info</h1>
<input id="input" type="text" placeholder="Enter 3 digit route ex 005" >
<input type="button" value="Get Route" onclick="getRoute()">
<br>
<p id = 'p'><span id="routeInfo"></span></p>
</div>
Javascript
$(document).ready(function() {
var route = $('#input');
getRoute.click(function() {
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&callback=myCallback&Route=" + route;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
var myCallback = function(data) {
var myarray = Array.prototype.slice.call(data);
document.getElementById("routeInfo").innerHTML = JSON.stringify(myarray);
}
});
});
It looks like you are jumping through a lot of hoops you don't need to. As long as you are using Jquery, you should look into getting the api data with an ajax request. It's much easier and more intuitive. Also you have a few problems such as trying to get the input value with var route = $('#input'); which return the actual input element. You are also processing the returned data in a way that won't work.
Here's a basic example to get you going on (IMO) a better track:
function getRoute() {
var route = $('#input').val();
var url = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&Route=" + route;
$.ajax({url: url, success: function(data){
var retValue = "";
var i = 0
for(i; i< data.length; i++) {
retValue += data[i].BridgeName + "<br>"
}
document.getElementById("routeInfo").innerHTML = retValue;
}});
}
If you intend functionality in the getRoute.click callback to run, you need to rewrite that as a method function getRoute(), or get the button element via jQuery and assign that to the variable getRoute. As it stands, you have the click method wired via the markup to a function named getRoute which does not exist. In the JS you are trying to register a click event to a jQuery object named getRoute which does not exist.
getRoute needs to be a global function for it to be called from html :
getRoute = (function() {
Also, myCallback needs to be a global function for it to be called from your loaded script (just remove the var):
myCallback = function(data) {
I have an API which should return some text JSon String.
http://api.census.gov/data/2010/sf1?get=P0010001&for=county:013&in=state:08
I wan to use JavaScript to query this API and display in the HTML element. The code looks like this:
//html
<input type="submit" value="Get City" onclick=" getpop()">
//JS:
function getpop() {
var nereq2 = new XMLHttpRequest();
nereq2.open("GET", "http://api.census.gov/data/2010/sf1?get=P0010001&for=county:013&in=state:08", true);
nereq2.onreadystatechange = function () {
if (nereq2.readyState == 4) {
var temp3 = nereq.response; **//problem start at here, which always return empty*******
document.getElementById("fs").innerHTML = temp3;
};
};
nereq2.send();
}
When I click the link it returns the JSon properly, however when I use the code to query, it returns empty. I don't know whether it related to the browser setup or there are some other issues?
You have a typo. nereq.response should be nereq2.response.
Working JSFiddle - (using https here because JSFiddle requires that)
How does one get the .tagName of a value passed in an HTML form input? This is to check whether the value that has been passed is an 'iFrame'. The input is to only accept iframes
For example:
//HTML
<input type="text" id="iFrame">
<button id="butt">Push</button>
//JavaScript
document.getElementById("butt").onclick = function(){
var iframe = document.getElementById("iFrame").value;
console.log(iframe.tagName);
}
I think you are looking for
var iframe = document.getElementsByTagName("iFrame")
I perhaps did not ask the question in the best way, initially.
I wanted to check if the value passed in the input field was an "iframe" (the input is to only accept iFrames). Since .value returns a string and not an HTML tag, getting the tag name through basic methods would not work. I needed another way.
For anybody else who needs a quick solution, this is how I managed to do it:
document.getElementById("submit").onclick = function(){
var iframe = document.getElementById("iFrame").value;
var check1 = iframe.match(/iframe/g);
var check2 = iframe.match(/frameborder/g);
var check3 = iframe.match(/http:/g);
var check = check1.length + check2.length + check3.length;
if (check === 4) {
alert("good!");
}
}
I am attempting to get all the form values into a normal array[]. I had it working for tags but then I added some tags and can't seem to get it.
With just tags it worked with this
var content = document.querySelectorAll("#form input[name='content[]']");
I am currently trying something like this
var content = document.elements["content[]"].value;
This form can change from user input down the road as each section of the form is a module that they choose to add. It is also important to get the values in order, if that isn't possible then I would need to make it a JSON array. Pure javascript or jquery is fine either way.
Thank you for any help.
EDIT
I used this to solve my problem
var contents=[]
var content = $('#form').serializeArray()
for (var i = 0; i < content.length; i++) {
contents[contents.length]=content[i].value
};
Try
html
<form id="form">
<input type="text" name="content[]" value="abc" />
<textarea name="textarea" value="">123</textarea>
</form>
js
$(function() {
var form = $("#form");
// escape `[]`
var content = form.find("input[name=content\\[\\]]");
// array `literal declaration`
var _arr = [content.prop("value")];
// map all form values to single array
var arr = $.map(form.serializeArray(), function(v, k) {
return [v.value]
});
// array literal with `textarea` `value`
var t = [$("textarea").prop("value")];
console.log(_arr, arr, t);
// _arr: `["abc"]` , arr:`["abc", "123"]` t:`["123"]`
})
Demo.
See Arrays
Can I do something like this?
var counter = SomeJSFunctionThatReturnsAvalue();
<tr><td> <input type="file" name="file-upload"+"_counter" id="file-upload" /></tr></td>
Can I do that? I need to append an underscore and an incremented number to the name.
Also, an off-topic question - that function above returns the value of an input type, for example:
<input type="hidden" name="hidden-input-type" value="2" />
Is the value "2" a number that I can use for math operations? If not, how can I make it one?
Here you go fella.
<head>
<script>
function test($count) {
document.getElementById("test1").setAttribute("name","file-upload_" + $count);
}
</script>
</head>
<body>
<p>some content</p>
<input id="test1" type="file" name="file-upload" id="file-upload" value="2"/>
<p>some other content</p>
<script>test(1);</script>
</body>
Your SomeJSFunctionThatReturnsAvalue(); would pass it to test() function.
to get the value of "2" from your second question for use in a math function, just do:
var value = document.getElementById("test1").getAttribute("value");
document.write(parseInt(value, 10) + 3);
which returns 5.
To append the return value of your function to the name of the input tag, you can assign it to the name attribute of the input.
var counter = SomeJSFunctionThatReturnsAvalue();
var fileUpload = document.getElementById('file-upload');
fileUpload.name = fileUpload.name + "_" + counter;
You can get the type of a variable by using "typeof"
typeof myValue; // "string"
You can change this to an integer by using the parseInt() function.
var intValue = parseInt(myValue, 10);
You can change the name using .setAttribute("name", theNameUwantToChangeTo);:
function changeName(number){
var ele = document.getElementById("file-upload");
ele.setAttribute("name", b.getAttribute("name")+ "_" + number);
}
changeName(number);
To get the value, just .value:
function getV(){
return document.getElementById("file-upload").value;
}
var number = getV();
In case it does not return int, use parseInt()
function getV(){
return parseInt(document.getElementById("file-upload").value);
}
var number = getV();
Maybe you would benefit from looking into Angular.js or Ember.js if you are trying to do things like this. They can do data binding so that you can make readable and dynamic code just like what you are trying to create in your question.
If not that^ then this:
I saw you mentioned in a comment that you are dynamically creating the list. That is where you should be assigning the correct name with the counter (assuming there's no desire for counter to change dynamically. If there is a dynamic change then tell us what events are doing the change) Could you show us the code that is doing that please?