i need to make it so that when a zip code is typed into the box and the submit button is clicked, the name of the city shows up under it. when i click the button after putting a zip code the city name doesn't show up. it says the error is that wallOfText is not a function but i'm not sure how to fix it. any help would be appreciated!! here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
Enter your zip code:<br><input type="text" id="zipBox" name="zipCode"><br><br>
<button onclick="weatherFunction()">Submit</button>
<p id="result"></p>
<script>
function weatherFunction() {
var zip = document.getElementById("zipBox").value;
jQuery(document).ready(function ($) {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?zip=" +zip+ ",us&appid=b3456f9acbfa64fc4495e6696ecdc9a5",
dataType: "jsonp",
success: function (wallOfText) {
city = wallOfText("name");
if (zip != null) {
document.getElementById("result").innerHTML = wallOfText;
}
}
});
});
}
</script>
</body>
</html>
The issue you have is that you're attempting to call wallOfText like it's a function, when in fact it's the object which has been deserialised from the response of the AJAX call. As such, you need to access the object's name property to set the city variable, then use that to set the text() of the #result element.
Note that the document.ready handler within the function is redundant, and you should be doing the zip value validation before you make the request. I also updated the logic to use jQuery to bind the event handler on the button instead of the outdated onclick attribute. Try this:
jQuery(function() {
$('#send').click(function() {
var zip = $("#zipBox").val();
if (zip !== '') {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?zip=" + zip + ",us&appid=b3456f9acbfa64fc4495e6696ecdc9a5",
dataType: "jsonp",
success: function(wallOfText) {
var city = wallOfText.name;
$("#result").text(city);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter your zip code:<br>
<input type="text" id="zipBox" name="zipCode" value="90210" /><br /><br />
<button type="button" id="send">Submit</button>
<p id="result"></p>
Related
I have a difficult question, I am trying to get the input value of an input field, however, I need this to happen within another function.
I already have code that works outside of this other function but I need to refactor it to work inside another function that I am calling.
Examples of working code and non-working code are below.
Here is the HTML where I am getting the input:
<!DOCTYPE HTML>
<HTML>
<head>
<title></title>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="css/styles.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/require.js"></script>
<script type="text/javascript">
(function () {
var config = {
baseUrl: "js",
};
var dependencies = ["otherFile"];
require(config, dependencies);
})();
</script>
</head>
<body>
<div>
<label>Input URL</label>
<input type="url" />
<p id="targetInput"></p>
</div>
</body>
</html>
Here is the non-working JS that I am trying to call within another function:
function someOtherFunction() {
var getCurrentInput = function() { };
var input = document.querySelector("input");
var log = document.getElementById("targetInput");
input.addEventListener("input", getCurrentInput);
var getCurrentInput = function (e) {
log.currentInput = e.target.value;
};
}
});
Lastly here is the working code that works outside of the scope of someOtherFunction
var getCurrentInput = "";
var input = document.querySelector("input");
var log = document.getElementById("targetInput");
input.addEventListener("input", getCurrentInput);
function getCurrentInput(e) {
log.currentInput = e.target.value;
}
Now you may notice that there isn't a form being submitted here, the reason for this is because this code is running on an iframe that is being called into another app. The submit is happening there but requires me to call a function to make it happen and technically isn't a submit, meaning I don't have control over it like a regular submit. This is why I need to call the current input value inside someOtherFunction.
Any help would be greatly appreciated here! Essentially I want to get the value inside the input and update my API with the value as a JSON string. There must be a better way!
Was a bit difficult to follow at first given the nesting, but something like this?
const doThing = (e) => {
let input = document.getElementById("input");
let log = document.getElementById("targetInput");
log.textContent = input.value;
}
<div>
<label>Input URL</label>
<input type="url" id="input"/>
<p id="targetInput"> </p>
</div>
<button onclick="doThing()">Click</button>
Essentially an external submit that takes an internal input value, and injects it into another internal element?
instructions for the project is to
create a simple web page application that allows the user to enter one or more stock ticker symbols and
display price information about these stocks.
• Data has to come from a REST API (https://www.alphavantage.co), it is free to use and returns JSON
formatted output.
Here is my code so far and I'm not being able to figure it out
UPDATED
when a user types a symbol, it's not showing anything on the console. how can I make it that for every symbol a user inputs , it fetches the price from the url and gives price.
$(document).ready(function() {
$('#searchstock').on('click', function() {
let requestData = $('search').val();
let resultElement = $('stock');
// Make request to rest API
$.ajax({
url: 'https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=' + requestData + '&apikey=SB1CZMKQ6Q5283QZ',
method: 'get',
data: {
symbols: requestData
},
dataType: 'json',
success: function(data) {
console.log(data);
resultElement.html('price:' + data.Stock_Quotes[0])
}
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Stocks</title>
<!-- Bootstrap core CSS -->
<link href="https://bootswatch.com/4/simplex/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="searchContainer">
<h1>Enter symbol</h1>
<p class="lead">Enter a a symbol to fetch a price </p>
<input type="text" id="search" class="form-control" placeholder="Stock symbol...">
</div>
<br>
<button type="button" id="searchstock" class="btn btn-info">Get price</button>
<br>
<div id="stock"></div>
</div>
<!-- /.container -->
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- script src="js/main.js"></script -->
</body>
</html>
You expected this line to match the input having its id attribute set to "search":
let requestData = $('search').val();
jQuery select function requires a CSS selector as its first argument. Now in your code, the CSS selector you give to $ function is'search' and this actually means «Please match elements having their name being "search"» and not «Match elements having their id attribute set to "search"».
Do you see the difference ?
Simply change $('search').val(); to $('#search').val(); as # tells to match the "id" attribute.
The same goes for this line.
let resultElement = $('stock');
You also have a property name issue.
Querying for "MSFT" will return something like:
{
// …
"Stock Quotes": [
{
"1. symbol": "MSFT",
"2. price": "93.0300",
"3. volume": "--",
"4. timestamp": "2018-03-02 15:59:59"
}
]
}
As you can see, the data object property is called "Stock Quotes" and not Stock_Quotes as you put it in your code.
As the property name contains space, square brackets notation is required to access this entry. Retrieving the price for the first result will look like this:
resultElement.html('price:' + data["Stock Quotes"][0]["2. price"])
Try making use of oninput instead of onclick if you want to execute search/ajax-call whenever a user types a symbol.
$('#search').on('input', function(e) {
var resultElement = $('#stock'),
requestData = $(this).val();
// Make request to rest API
$.ajax({
url: 'https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=' + requestData + '&apikey=SB1CZMKQ6Q5283QZ',
method: 'get',
data: {
symbols: requestData
},
dataType: 'json',
success: function(data) {
console.log(data);
resultElement.html('price:' + data["Stock Quotes"][0]["2. price"])
}
});
});
In a class, I was asked to make a dynamic drop-down menu in a form using HTML5 and JavaScript. I did that here.
Now, I need to call data from a JSON file. I looked at other answers on SOF and am still not really understanding how to use JQuery to get info from the JSON file.
I need to have 2 fields: the first field is a Country. The JSON key is country and the value is state. A copy of the JSON file and contents can be found here. The second drop-down field adds only the values / arrays related to its associated Country.
Here is a copy of my HTML5 file:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
Here is a copy of the JS file I wrote so far that tries to get the data from the JSON file and fails:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the content from the other JS file that adds the field instruction:
var selectYourCountry = document.getElementById('selectCountry');
selectYourCountry.innerHTML = "Select Your Country: ";
var selectYourState = document.getElementById('selectState');
selectYourState.innerHTML = "Select Your State";
This was supposed to at least add the values to the field, but nothing but empty boxes appear on the web page.
I then need to make a conditional statement like the one at here but calling or referencing data from the JSON file.
I have only taken some HTML and JavaScript courses, not JQuery and JSON. So, your help will greatly increase my knowledge, which I will be very grateful for.
Thank you!!
I found this SOF answer and changed my JS file to the following:
$(document).ready(function()
{
$('#locationSelector').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"countryState.JSON",
dataType: "json",
success: function (data) {
$.each(data.country,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#locator');
});
}
});
});
});
And, I edited my HTML document as follows:
<form id="locationSelector" enctype='application/json'></form>
I removed and added back the <select> tags and with the following at least I get a blank box:
`<form id="locationSelector" enctype='application/json'>
<select id="locator"></select>
</form>`
I feel like I am getting closer, but am still lost.
Can you try this:
$.get("countryState.JSON", function( data ) {
var html = "";
$.each(data.d, function(i, el) {
console.log(el);
html += "<option value='"+Your value+"'>"+Your displayed text+"</option>";
});
$('#state').html(html);
});
I'm trying to get the user to input a search term, and then use that term as a tag to search Flickr's API. I managed to get the basic search working, but something has gone wrong between that and adding the button click event. Can someone put me right? I feel like it's something little that I'm not seeing, I'm pretty new to jqueryand json.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
$("button").click(function() {
var searchTerm = $("input:text").val();
var flickrApi = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON(flickrApi, {
tags: "searchTerm",
tagmode: "any",
format: "json"
})
.done(function(data) {
$.each(data.items, function(i, item) {
$("<img>").attr("src", item.media.m).appendTo("#images");
if (i === 3) {
return false;
}
});
});
})
</script>
</head>
<body>
<input type="text" id="search">
<button type="submit">Search</button>
<div id="images"></div>
</body>
</html>
Try removing double quotes in your variable "searchTerm" changing:
$.getJSON( flickrApi, {
tags: "searchTerm",
tagmode: "any",
format: "json"
})
to
$.getJSON( flickrApi, {
tags: searchTerm, // Local variable.
tagmode: "any",
format: "json"
})
Btw, you need to place your code inside a jQuery function. The jQuery functionality will successfully run when the DOM is ready to interact with HTML tags through jQuery/Javascript code.
$(document).ready(function()
{
// jQuery/Javascript code goes here...
});
Or the shorthand for $(document).ready():
$(function()
{
// jQuery/Javascript code goes here...
});
Demo
Suppose I have 2 html files: form.html and confirm.html
form.html just have a text field and a submit button, when you hit submit it will display what you just typed in text field.
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<script type="text/javascript">
function display(){
document.write("You entered: " + document.myform.data.value);
}
</script>
</HEAD>
<BODY>
<center>
<form name="myform">
<input type="text" name="data">
<input type="submit" value="Submit" onClick="display()">
</form>
</BODY>
</HTML>
Now I want that when hit submit button it will display entered value in confirm.html. What should I do? I mean what should be in confirm.html and how data from form.html be used in other location, do I need create a separate JavaScript file to store JS function so I can use it in both 2 html files. I am kind of new to all kind of stuff.
Note: No PHP or server side language or anything super here, just 2 html files in my Desktop and I want to test using FireFox.
Thank you!
You can try using localStorage or cookies. Check one of the 2 solutions found below...
1 - If you have HTML5, you can store the content of you input into the localStorage.
Try this example:
form.html:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into localStorage
localStorage.setItem("mytext", mytext);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="confirm.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
confirm.html:
<html>
<head>
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var mytext = localStorage.getItem("mytext");
// Writing the value in the document
document.write("passed value = "+mytext);
}
</script>
</head>
<body onload="init();">
</body>
</html>
2 - Also, as #apprentice mentioned, you can also use cookies with HTML standards.
Try this example:
form.html:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
// Function for storing to cookie
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into a cookie
setCookie("mytext", mytext, 300);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="confirm.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
confirm.html:
<html>
<head>
<script>
// Function for retrieveing value from a cookie
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into a cookie
var mytext = getCookie("mytext");
// Writing the value in the document
document.write("passed value = "+mytext);
}
</script>
</head>
<body onload="init();">
</body>
</html>
What you could do is submit the form using a get method (method="get"), and send it to your confirm.html page (action="./confirm.html").
Then, you could use jQuery to retrieve the values from the URL from your confirm.html page.
This website provides a method to do that: http://jquerybyexample.blogspot.com/2012/06/get-url-parameters-using-jquery.html .
Then, all you have to do is call your display() method.
Seams like a fit for persist.js, which will let you save and load data in the user's browser. After including its javascript file, you can save data like this:
var store = new Persist.Store('My Application');
store.set('some_key', 'this is a bunch of persistent data');
And you can later retrieve the saved data in another html page like the following:
var store = new Persist.Store('My Application');
val = store.get('some_key');
You could also, instead of changing the page, change the content of the page. Upon submission just change the page using the innerHtml variable.