So this is externally linked, that works fine. But when I run it in the browser, it does not show anything. Is there anything wrong with this code?
var myheading = "This is my webpage!";
var text = "This JavaScript file makes use of Variables";
var linktag = "http://www.google.com/";
var begineffect = "<strong>";
var endeffect = "</strong>";
var linebreak = "<br />";
function numberone(myheading) {
document.write("<h2>" +myheading+ "</h2>");
}
numberone(myheading)
function numbertwo(text) {
document.write("<strong>" +text+ "</strong>");
}
numbertwo(text)
function numberthree(linktag) {
document.write( +linktag+ );
}
numberthree(linktag)
There are two extra + to remove in the document.write of the 'numberthree' function, i.e.:
var myheading = "This is my webpage!";
var text = "This JavaScript file makes use of Variables";
var linktag = "http://www.google.com/";
var begineffect = "<strong>";
var endeffect = "</strong>";
var linebreak = "<br />";
function numberone(myheading) {
document.write("<h2>" +myheading+ "</h2>");
}
numberone(myheading)
function numbertwo(text) {
document.write("<strong>" +text+ "</strong>");
}
numbertwo(text)
function numberthree(linktag) {
document.write(linktag);
}
numberthree(linktag)
Related
I am using MapBox to render a map. I have made a onClick function wherein when clicked on the map it shows the geocode information shown in the screenshot below through api.
Now what I want is to have a button below the table and when click on it I want it to execute a particular function, I have defined it but when clicked on it says Function is not defined
Code
map.current.on('click', function(e) {
var coordinates = e.lngLat;
var lng = coordinates.lng;
var lat = coordinates.lat;
console.log(lat);
console.log(lng);
var d = fetch("https://api.mapbox.com/geocoding/v5/mapbox.places/" + lng + "," + lat + ".json?access_token={token_value}").then(response => response.json()).then(function(data) {
console.log(data)
var str = "<table border='1'><tr><td><center>Title</center></td><td><center>Content</center></td></tr>"
for (let i in data["features"]) {
str = str + "<tr><td style='padding:5px'>" + data["features"][i]["place_type"][0] + "</td><td style='padding:5px'>" + data["features"][i]["place_name"] + "</td></tr>"
}
str = str + "</table>"
// button
str = str + "<button onClick={myFunction}>Save</button>"
function myFunction() {
console.log('Saved pressed');
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(str)
.addTo(map.current)
});
console.log(d);
});
Fix code as below
// button
str += `<button onclick="myFunction()"}>Save</button>`;
I would guess the button (and the function name defined for it) are created with a different scope than where you have defined your function. One of these might work:
Define your function as const myFunction = () => console.log("saved pressed").
Try referencing your function as this.myFunction
I'm trying to parse XML by using AJAX. However there were a few errors which i got saying my "html is not defined"
Basically what I want to do is to parse a specific amount of data from my XML codes and display it using HTML webpage .
The below is the list of bugs in console when I tried to run the script
at displayCountrylist (test2.html:136)
at handleStatusSuccess (test2.html:61)
at readyStateChangeHandler (test2.html:32)
at XMLHttpRequest.xhttp.onreadystatechange (test2.html:16)
I tried to do everything to debug but still failed. Any one help please?
<html>
<script>
function makeAjaxQueryCountrylist()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
readyStateChangeHandler(xhttp);
};
xhttp.open("GET", "A3_CtryData_dtd_Sample.xml", true);
xhttp.send();
}
function readyStateChangeHandler(xhttp)
{
if (xhttp.readyState == 4)
{
if(xhttp.status == 200)
{
handleStatusSuccess(xhttp);
}else
{
handleStatusFailure(xhttp);
}
}
}
function handleStatusFailure(xhttp){
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
function handleStatusSuccess(xhttp)
{
var xml = xhttp.responseXML;
var countrylistObj = parseXMLCountrylist(xml);
displayCountrylist(countrylistObj);
}
function parseXMLCountrylist(xml)
{
var countrylistObj = {};
var countrylistElement = xml.getElementsByTagName("CountryList")[0];
var recordElementList = countrylistElement.getElementsByTagName("CountryRecord");
countrylistObj.recordList = parseRecordElementList(recordElementList);
return countrylistObj;
}
function parseRecordElementList(recordElementList)
{
var recordList = [];
for(var i=0; i < recordElementList.length; i++)
{
var recordElement = recordElementList[i];
var recordObj = parseRecordElement(recordElement);
recordList.push(recordObj);
}
return recordList;
}
function parseRecordElement(recordElement)
{
var recordObj = {};
var countrycodeElement = recordElement.getElementsByTagName("country-code")[0];
recordObj.countrycode = Number(countrycodeElement.textContent);
var nameElement = recordElement.getElementsByTagName("name")[0];
recordObj.name = nameElement.textContent;
var alpha2Element = recordElement.getElementsByTagName("alpha-2")[0];
recordObj.alpha2 = alpha2Element.textContent;
var alpha3Element = recordElement.getElementsByTagName("alpha-3")[0];
recordObj.alpha3 = alpha3Element.textContent;
var capitalcityElement = recordElement.getElementsByTagName("capital-city")[0];
recordObj.capitalcity = capitalcityElement.textContent;
return recordObj;
}
function displayCountrylist(countrylistObj)
{
for(var i=0; i < countrylistObj.recordList.length; i++)
{
var recordObj = countrylistObj.recordList[i];
html += "country-code: " + recordObj.countrycode;
html += "<br />";
html += "name: " + recordObj.name;
html += "<br />";
html += "alpha-2: " + recordObj.alpha2;
html += "<br />";
html += "alpha-3: " + recordObj.alpha3;
html += "<br />";
html += "capital-city: " + recordObj.capitalcity;
html += "<br />";
}
var displayDiv = document.getElementById("display1");
displayDiv.innerHTML = html;
}
</script>
<body>
<button onClick="makeAjaxQueryCountrylist()"> Region Info I (Format: region-fmt-1.xsl)</button>
<br /><br />
<div id="display1">
</div>
</body>
</html>
There isn't any problem with my XML codes so it has to be some error from here.
You got that error html is not defined because you are using html variable without declaring it. So, before the line
html += "country-code: " + recordObj.countrycode;
you have to write
let html = '';
here is my code. I would like to print the variable 'fName' and the text prior into the div (with the ID 'feedback').
<script>
function myFunction() {
var first = document.getElementById("fName").value;
var last = document.getElementById("lName").value;
document.getElementById("feedback").innerHTML += "Hello" + fName;
}
</script>
Any help would be appreciated.
Just use the variables you have defined:
<script>
function myFunction() {
var first = document.getElementById("fName").value;
var last = document.getElementById("lName").value;
document.getElementById("feedback").innerHTML += "Hello " + first + " " + last;
}
</script>
I'm working on a weather api and I'm having trouble toggling between Celsius and Fahrenheit.
I used a separate function to get the location as well as call from the API.
I also added an onclick function within this second function. I can get it to toggle to one temperature but not back.
function getTemp(data) {
// API variables
var temp1 = data.main.temp;
var weatherUrl = data.weather[0].icon;
var tempInC = Math.round(temp1); // Temp in Celsius
var tempInF = Math.round(temp1 * 9/5 +32)
// Inner HTML variables
var weatherF = "The weather is " + tempInF + " ℉ <br>" +
"<img src='" + weatherUrl + "'/>";
var weatherC = "The weather is " + tempInC + " ℃ <br>" +
"<img src='" + weatherUrl + "'/>";
// Button DOM variables
var buttonText = document.getElementsByTagName("button")[0].innerText;
var buttonId = document.getElementById('btn');
x.innerHTML = weatherF;
buttonId.onclick = function toggleTemp() {
if(buttonText == "Convert to Celsius") {
x.innerHTML = weatherC;
buttonId.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = weatherF;
buttonId.innerText = "Convert to Celsius";
}
}
}
I used innerText because I thought it was the easiest way to toggle back and forth between temp. I can get the weather to convert to Celsius, but the else statement is not working. Fyi, I was not able to get the button text to change using the tag name which is why I resorted to using an id in the button click function. I'm still pretty new at Javascript. Any help would be appreciated.
You need to update the buttonText variable when you toggle the text of buttonId.
buttonId.onclick = function toggleTemp() {
if (buttonText == "Convert to Celsius") {
x.innerHTML = weatherC;
buttonText = buttonId.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = weatherF;
buttonText = buttonId.innerText = "Convert to Celsius";
}
}
Your variable x is undefined. In the future, try to avoid using the innerHTML property, which can break event listeners and be slow to render.
Neither buttonText nor x are defined in the scope of your onclick function, which might be why nothing happens. Have you checked the console for errors?
function getTemp(data) {
// API variables
var temp1 = data.main.temp;
var weatherUrl = data.weather[0].icon;
var tempInC = Math.round(temp1); // Temp in Celsius
var tempInF = Math.round(temp1 * 9/5 +32)
// Inner HTML variables
var weatherF = "The weather is " + tempInF + " ℉ <br>" +
"<img src='" + weatherUrl + "'/>";
var weatherC = "The weather is " + tempInC + " ℃ <br>" +
"<img src='" + weatherUrl + "'/>";
// Button DOM variables
var x = ...; // Declare x for the function scope here
var buttonText = document.getElementsByTagName("button")[0].innerText;
var buttonId = document.getElementById('btn');
x.innerHTML = weatherF;
buttonId.onclick = (function (x, wC, wF, btn) {
return function () {
// Change DOM
if(btn.innerText == "Convert to Celsius") {
x.innerHTML = wC;
btn.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = wF;
btn.innerText = "Convert to Celsius";
}
};
})(x, weatherC, weatherF, document.getElementsByTagName("button")[0])
}
I've added a sample Javascript array in my web. Funny that it works in jsfiddle but unfortunately not working in Eclipse JSP. Here's the code.
Javascript:
var titles = [];
var names = [];
var tickets = [];
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
var messageBox = document.getElementById("display");
function insert() {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
function clearAndShow () {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
jsfiddle link
You should wait for the page to finish loading all its elements.
You can either do:
window.onload=function(){
// Do stuff here
};
Or if you are using jQuery:
jQuery(document).ready(function(){
// Do stuff here
});