How to call javascript function multiple times? - javascript

I am using an API from OpenWeatherMap on my website to show weather condition of just some specific places only, altogether in one page.
Here's the code:
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<body>
<input type="hidden" name="name" value="dehradun" id="cityName">
<button onclick="getWeather()">Get weather of Dehradun</button>
<div class="weatherResponse"></div>
<br><br>
<input type="hidden" name="name" value="pune" id="cityName">
<button onclick="getWeather()">Get weather of Pune</button> '
<div class="weatherResponse"></div>
<br><br>
<script>
function getWeather() {
$('.weatherResponse').html('');
var cityName = $('#cityName').val();
var apiCall = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&mode=json&units=metric&appid=<apikey>';
$.getJSON(apiCall, weatherCallback);
function weatherCallback(weatherData) {
var cityName = weatherData.name;;
var country = weatherData.sys.country;
var description = weatherData.weather[0].description;
var temp = weatherData.main.temp;
$('.weatherResponse').append("The Weather in " + cityName + " " + country + " is currently " + description + " with temperature: " + temp);
}
}
</script>
</body>
Suppose if i want to show weather condition of two places using the same Javascript function then its showing the same result for both the places(Of place (Dehradun) mentioned first in code).
Help me solve this problem.

You can Pass both your city name and div (display results) as function parameter
function getWeather(cityName, className)
{
$('.'+className+'').html('');
var apiCall= 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&mode=json&units=metric&appid=d3d913fca612366a61837ea39a622480';
$.getJSON(apiCall,weatherCallback);
function weatherCallback(weatherData)
{
var cityName= weatherData.name;;
var country= weatherData.sys.country;
var description= weatherData.weather[0].description;
var temp= weatherData.main.temp;
$('.'+className+'').append("The Weather in " + cityName + " " + country + " is currently " + description + " with temperature: " + temp);
}
}
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<body>
<button onclick="getWeather('dehradun','wr1')">Get weather of Dehradun</button>
<br><br>
<div class="wr1"></div>
<br><br>
<button onclick="getWeather('pune','wr2')">Get weather of Pune</button>
<br><br>
<div class="wr2"></div>
<br>
</body>

I have roughly added the working code below, when you click on a button it will show the whether report of that city in both the text, Try clicking on both the button and take a look:
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<body>
<input type="hidden" name="name" value="dehradun" id="cityName2">
<button onclick="getWeather('dehradun')">Get weather of Dehradun</button>
<div class="weatherResponse"></div>
<br><br>
<input type="hidden" name="name" value="pune" id="cityName1">
<button onclick="getWeather('pune')">Get weather of Pune</button>
<br><br>
<div class="weatherResponse"></div>
<script>
function getWeather(cityName){
$('.weatherResponse').html('');
var apiCall= 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&mode=json&units=metric&appid=d3d913fca612366a61837ea39a622480';
$.getJSON(apiCall,weatherCallback);
function weatherCallback(weatherData){
var cityName= weatherData.name;;
var country= weatherData.sys.country;
var description= weatherData.weather[0].description;
var temp= weatherData.main.temp;
$('.weatherResponse').append("The Weather in " + cityName + " " + country + " is currently " + description + " with temperature: " + temp);
}
}
</script>
</body>

Related

How to change the font color of variable after show result in JavaScript?

I'm a beginner in JavaScript and I'm trying to change the color of variable/element (name, age, and status) when it show the output in my JavaScript coding. For some reason the output not appear. Here is the code below:
<html>
<head>
<script>
function ageCalculator() {
var name = document.getElementById("name").value;
var birthdate = document.getElementById("dob").value;
var dob = new Date(birthdate);
var status;
if(birthdate==null || birthdate=='') {
document.getElementById("message").innerHTML = "<br><br>Choose a date properly!";
return false;
} else {
var month_diff = Date.now() - dob.getTime();
var age_date = new Date(month_diff);
var year = age_date.getUTCFullYear();
var age = Math.abs(year - 1970);
if (age<20)
status = "You are still young!";
else if (age>=20 && age<=25)
status = "Now start thinking to have your own family!";
else
status = "Be responsible and care about others!";
return document.getElementById("result").innerHTML =
" Hello " + name.css('color','red') + "<br><br> You are " + age.css('color','red') + " year-old" + "<br><br>" + status.css('color','red');
}
}
</script>
</head>
<body>
<center>
<b> Enter your name : <input type="text" id="name" name="name" ><br><br>
<b> Enter your birthday: <input type=date id = dob> </b>
<span id = "message" style="color:darkred"> </span> <br><br>
<button type="submit" onclick = "ageCalculator()"> Submit </button> <br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4 id="result" align="center"></h4>
</center>
</body>
</html>
Here is the sample of the output:
enter image description here
You can add a CSS class in style tag and add a span tag around the text where you want to apply the style.
Add below style tag in your head element.
<style>
.txtColor {
color: red;
}
</style>
Now, in the innerHTML, add the span tag and apply the styles.
return document.getElementById("result").innerHTML =
" Hello <span class='txtColor'>" + name + "</span><br><br> You are <span class='txtColor'>" + age + "</span> year-old" + "<br><br><span class='txtColor'>" + status + "</span>";
Please mark this as an answer if it helps.

Storing </input> data to host

I'm just working with HTML and JavaScript and I have a question regarding working with </input> elements and this is one of my inputs:
<input size="4" class="PanInput" id="W_PAN4" name="W_PAN4" maxlength="4" autocomplete="off" onkeypress="return numericOnKeypress(event)" onkeyup="nextTabs(this, false, event)" value="" tabindex="1" dir="ltr" onpaste="doNotPaste()" onfocus="getName(this)" type="text" width="200">
And I made an alert() after a submit button:
<form method="post" name="receiptForm" action="https://google.com" accept-charset="UTF-8" onclick="othername">
<script>
function othername() {
var input1 = document.getElementById("W_PAN4").value;
var input2 = document.getElementById("W_PAN3").value;
var input3 = document.getElementById("W_PAN2").value;
var input4 = document.getElementById("W_PAN1").value;
var userCardID = input1 + " " + input2 + " " + input3 + " " + input4;
var input_pass = document.getElementById("W_PIN").value;
var input_CVV2 = document.getElementById("W_CVV2").value;
var input_expire_month = document.getElementById("W_EXPIRE1").value;
var input_expire_year = document.getElementById("W_EXPIRE2").value;
var input_all = userCardID + " " + "2nd_Password = " + input_pass + " " + "CVV2 = " + input_CVV2 + " " + "ExpireDateYear = " + input_expire_year + " " + "ExpireDateMonth = " + input_expire_month;
alert(input_all);
}
I want to have a function similar to this:
<script type="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("Location_Here", True);
s.writeline(document.passForm.input1.value);
s.writeline(document.passForm.input2.value);
s.writeline(document.passForm.input3.value);
s.Close();
}
</script>
I mean I want to store those inputs data as a .txt file on localhost or even in an online host.
What is the easiest way to save these data? Format is not important, I can deal with anything E-mail, File and etc. I think it is a server-side work. Any code will be appreciated.

Why won't my my mad lib compile?

So I have to use javascript and html to make a mad lib. I am asking the user to enter values and then hit the button and it is supposed to generate a story using the values they entered.
Here is my HTML:
<ul>
<li>Your Name: <input type="text" id="name"></li>
<li>Adjective: <input type="text" id="adjective"></li>
<li>State: <input type="text" id="state"></li>
<li>Animal: <input type="text" id="animal"></li>
<li>Month: <input type="text" id="month"></li>
<li>Adjective: <input type="text" id="adjective2"></li>
<li>Animal: <input type="text" id="animal2"></li>
<li>Object: <input type="text" id="object"></li>
</ul>
<button id="ready-button">Ready</button>
<div id="story"></div>
<script>
function madLib() {
var storyDiv = document.getElementById("story");
var adjective = document.getElementById("adjective").value;
var noun = document.getElementById("noun").value;
var state = document.getElementById("state").value;
var animal = document.getElementById("animal").value;
var month = document.getElementById("month").value;
var adjective2 = document.getElementById("adjective2").value;
var animal2 = document.getElementById("animal2").value;
var object = document.getElementById("object").value;
storyDiv.innerHTML ="One day, " + name + " was in the backwoods of " + state + " riding their pet " + animal + " it wasn't often that " + name + " got the chance to do this so they always made the most of their adventure. Usually, it was a fun experience until that one day in " + month + " they were minding their own business when all of the sudden the " + adjective2 + " " + animal2 + " jumped out from behind a small " + object + ". " + name + " could not beieve what they were seeing.";
}
var readyButton = document.getElementById('ready-button');
readyButton.addEventListener('click', madLib);
</script>
It seems that you got "noun" mixed up with "name" when grabbing the values for your story.
You have <input type="text" id="name"></li> and you use the name variable in your story a few times, but in the madLib function you have
var noun = document.getElementById("noun").value;
//document.getElementById("noun") will be undefined because there is no "noun element"
which should probably be
var name = document.getElementById("name").value;

Java script undefined variable, basic html form

I've been struggling with this for around an hour now and rewrote it about three different times and I can't for the life of me figure out what the issue is, regardless of what is entered, everything besides for the name field will return a value, however the name will just return undefined. I've gone over this so many times, I've copy+pasted+modified the working ones, there's not a single typo that I can find... What is going on here?
Item Name: <input type="text" id="item_name" placeholder="Enter a price..."/> </br>
Item Price: <input type="text" id="item_price" placeholder="Enter a price..."/> </br>
Item Description: <input type="text" id="item_description" placeholder="Enter a description..."/> </br>
Item Image(link): <input type="text" id="item_image" placeholder="Enter a image link..."/> </br>
rsid: <input type="text" id="rs_item_id" placeholder="Enter a item id..."/> </br>
rsam: <input type="text" id="rs_item_amount" placeholder="Enter a item amount..."/> </br>
<button id="update">Update item</button>
<script>
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
var button = document.getElementById("update");
button.addEventListener("click", function() {
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
</script>
The problem is that because you make them all global variables the name one clashes with the window.name property.
Either using a different variable name, or creating a closure will work
Put name, price, desc, img, rsid, rsam inside event handler.
var button = document.getElementById("update");
button.addEventListener("click", function() {
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
Demo: http://jsbin.com/fivos/1/edit?html,output

How to obtain text from a textbox in Javascript

UPDATE
Ok, after trying ".value" for god knows x amount of time again, it some how worked..... Problem solved. Thanks a lot for those who has responded.
UPDATE
How can I obtain the text(strings) from my form on my HTML page with Javascript?
I just want to take whatever was inputted into the text box and write into my XML file.
For example, if I type "HELLO" into the text box, I want "HELLO" written in the XML file.
I have tried both ".value" and ".text", they don't work. Also tried ".textcontent", no good too. I'm thinking that I need to use a different code.
Here's an image of what I'm trying to do:
http://img94.imageshack.us/img94/5677/sdfsdfsdfs.jpg
Here are the files if you want to mess with them personally:
http://www.mediafire.com/?e29t6ipatsqun70
Here's my HTML file:
<html>
<!--onSubmit="SaveXML(person);"-->
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
</head>
<body>
<script type="text/javaScript" src="LoginJS.js"> </script>
<script type="text/javaScript" src="writeXML.js"> </script>
<div class="form">
<form id="Registration" name="reg" action="" method="get" onSubmit="initialize_array()">
Username:<input type="text" name="Usrname" id="Usrname" maxlength="10"/> <br/>
Password:<input type="password" name="Pswd" id="Pswd" maxlength="20"/> <br/>
<hr>
PersonID:<input type="text" name="PersonID" id="PersonID"/> <br>
<hr>
First Name:<input type="text" name="FirstName" id="FirstName"/> <br>
Last Name:<input type="text" name="LastName" id="LastName"/>
<hr>
DOB:<input type="text" name="DOB" id="DOB"/> <br>
<hr>
Gender:<input type="text" name="Gender" id="Gender"/> <br>
<hr>
Title:<input type="text" name="Title" id="Title"/> <br>
<hr>
<!--Secret Question:<br>
<select name="secret?">
</select> <br>
Answer:<input type="text" name="answer" /> <br> <br>-->
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Here's my Javascript file:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'G:\\CST2309 - Web Programming 1\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var usrn = document.getElementById("Username").text;
var pswd = document.getElementById("Pswd").text;
var pid = document.getElementById("PersonID").text;
var fname = document.getElementById("FirstName").text; //This is where I'm having trouble with
var lname = document.getElementById("LastName").text;
var gender = document.getElementById("Gender").text;
var dob = document.getElementById("DOB").text;
var title = document.getElementById("Title").text;
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++) {
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '"');
file.WriteLine('></Person>\n');
} // end for countr
file.Write(' <Person ');
file.Write('Usrname="' + usrn + '" ');
file.Write('Pswd="' + pswd + '" ');
file.Write('PersonID="' + pid + '" ');
file.Write('FirstName="' + fname + '" ');
file.Write('LastName="' + lname + '" ');
file.Write('Gender="' + gender + '" ');
file.Write('DOB="' + dob + '" ');
file.Write('Title="' + title + '" ');
file.WriteLine('></Person>\n');
file.WriteLine('</PersonInfo>\n');
file.Close();
} // end SaveXML function --------------------
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
You can use document.getElementById("UsrName").value to get tha value of a field in your form. Due to you use id for every field, so there is no problem using this code.
Something around: http://www.tek-tips.com/viewthread.cfm?qid=1143011&page=1
Here is an example of it working. I changed some functionality around just to show that the function was seeing the values correctly:
http://jsfiddle.net/73gbH/1
But like everyone said change .text to .value

Categories