I am working with the OpenWeatherMap API and can't seem to figure out why one of my fields is showing up undefined. Everything is working except for when I try to retrieve the weather condition, which is located at weather.description, it is returning undefined. All of the other variables fill in fine. Anyone know what could be preventing this from working correctly?
My JavaScript:
var request = new XMLHttpRequest();
function getWeather() {
var latitude = document.getElementById("lat").value;
var longitude = document.getElementById("long").value;
request.open('GET', 'https://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&units=imperial&appid=547fa6dfa44cff13fa92bba2c465b366', true);
request.send();
request.onreadystatechange = displayData;
}
function displayData() {
if(request.readyState === 4 && request.status === 200) {
var resultData = JSON.parse(request.responseText);
var location = document.getElementById("location")
var temperature = document.getElementById("temperature");
var windspeed = document.getElementById("windspeed");
var condition = document.getElementById("condition");
location.value = resultData.name +", " + resultData.sys.country;
temperature.value = resultData.main.temp + " degrees Fahrenheit";
windspeed.value = resultData.wind.speed + " miles per hour";
condition.value = resultData.weather.description;
document.getElementById("resultset").style.visibility = "visible";
}
}
// Create an event handler for when the btn button is clicked
window.onload = function() {
var btn = document.getElementById("btn");
btn.addEventListener("click", getWeather, false);
}
My HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta id="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<header>
<h1>Weather Report</h1>
</header>
<article>
<h2>Weather Data</h2>
<table style="width:100%">
<tr>
<th><strong>City</strong></th>
<th><strong>Coordinates</strong></th>
</tr>
<tr>
<td>Batavia, OH, US</td>
<td>Latitude: 39.07859<br>
Longitude: -84.17941</td>
</tr>
<tr>
<td>Cincinnati, OH, US</td>
<td>Latitude: 39.10713<br>
Longitude: -84.50413</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
<form action="#" method="post" id="theForm" novalidate>
<fieldset id="coordinateset">
<label for="lat" id="latlabel">Latitude:</label>
<input id="lat" type="number" />
<label for="long" id="longlabel">Longitude:</label>
<input id="long" type="number" />
</fieldset><br><br>
<fieldset id="resultset">
<label for="location" id="locationlabel">Location:</label>
<input id="location" type="text" readonly />
<label for="temperature" id="temperaturelabel">Temperature:</label>
<input id="temperature" type="text" readonly />
<label for="windspeed" id="windspeedlabel">Wind Speed:</label>
<input id="windspeed" type="text" readonly />
<label for="condition" id="conditionlabel">Weather Condition:</label>
<input id="condition" type="text" readonly />
</fieldset>
</form>
<button id="btn">Submit Coordinates</button>
</article>
<script src="js/weather_report1.js"></script>
</body>
</html>
If you see the API at the OpenWeatherMap site, we see that the weather property is an array. To access the weather's description, try weather[0].description, or better yet, loop through it and extract each weather condition's description if it suits your use case.
Related
hello I'm working on a simple project where a user inputs the information and it goes into a table. I want the user to have the ability to put in the URL for an image and have it show up when the cell is made in the table. I have a button that prompts the user to input a URL but I cant figure out how to put that into an image tag inside the created cell.
let id = 0;
let img = document.getElementById("image").addEventListener("click", () => {
function getUrl() {
var url = prompt("Enter image URL");
if (url) {
return url;
} else {
return getUrl();
}
}
image.src = getUrl();
});
document.getElementById("add").addEventListener("click", () => {
let table = document.getElementById("list");
let row = table.insertRow(1);
row.setAttribute("id", `
test - $ {
id
}
`);
row.insertCell(0).innerHTML = document.getElementById("image").src = ""
row.insertCell(1).innerHTML = document.getElementById("Game-name").value;
row.insertCell(2).innerHTML = document.getElementById("hours-played").value;
row.insertCell(3).innerHTML = document.getElementById("new-critic-score").value;
row.insertCell(4).innerHTML = document.getElementById("new-personal-score").value;
let actions = row.insertCell(5);
actions.appendChild(createDeleteButton(id++));
document.getElementById("Game-name").value = "";
document.getElementById("hours-played").value = "";
document.getElementById("new-critic-score").value = "";
document.getElementById("new-personal-score").value = ""
});
function createDeleteButton(id) {
let btn = document.createElement("button");
btn.className = "btn btn-primary";
btn.id = id;
btn.innerHTML = "Delete";
btn.onclick = () => {
console.log(`
Deleting row with id: test - $ {
id
}
`);
let elementToDelete = document.getElementById(`
test - $ {
id
}
`);
elementToDelete.parentNode.removeChild(elementToDelete);
};
return btn;
}
<!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.0" />
<title>Document</title>
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css" />
</head>
<body class="container" style="background-color: rgb(3, 27, 63);">
<!--Using HTML, Bootstrap, and JavaScript create a single page website that contains the following:
a. A Bootstrap styled table representing your choice of data.
b. A Bootstrap styled form that allows users to add input data as a new row to the table when submitted.
-->
<br />
<div class="card" style="background-color: rgb(7, 59, 75);color: rgb(255, 255, 255);">
<div class="card-body">
<div class="row">
<div class="col-sm">
<div>
<label for="new-critic-score">Critic score</label>
<input type="text" class="form-control" id="new-critic-score" placeholder="score out of 100" />
</div>
</div>
<div class="col-sm">
<div>
<label for="new-personal-score">Personal score</label>
<input type="text" class="form-control" id="new-personal-score" placeholder="score out of 100" />
</div>
</div>
<div class="col-sm">
<div>
<label for="hours-played">Hours played</label>
<input type="text" class="form-control" id="hours-played" placeholder="hours" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm">
<div>
<label for="Game-name">Game name</label>
<input type="text" class="form-control" id="Game-name" placeholder="Game title" />
</div>
</div>
</div>
<div class="col-sm">
<div> <br>
<button id="image" class="btn btn-secondary from-control">add image</button>
<button id="add" class="btn btn-primary from-control">Create</button>
</div>
</div>
</div>
</div>
<table id="list" class="table table-dark table-striped">
<tr>
<th>game image</th>
<th>games played</th>
<th>Hours played</th>
<th>critic score</th>
<th>personal score</th>
<th>Actions</th>
</tr>
</table>
<script src="index.js"></script>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
</body>
</html>
<img src="" alt="">
It wasn't clear to me how you wanted to do it, I basically got the URL and stored it in a var to then make another variable that is the image element itself, using the stored URL.
let imgURL;
let imgElement;
document.getElementById("image").addEventListener("click", () => {
imgURL = prompt("Enter image URL");
imgElement = '<img src="' + imgURL + '" width="80px">';
});
I also did the deletion in a similar way. Creating the element with an onclick to a function that passes the element itself with this as a parameter.
let deleteButton = '<input type="button" value="Delete" onclick="deleteRow(this)">'
and
row.insertCell(5).innerHTML = deleteButton;
Getting the ID by working your way up the parent elements to find the rowIndex.
function deleteRow(row) {
var id = row.parentNode.parentNode.rowIndex;
document.getElementById("list").deleteRow(id);
}
Hope the code itself helps you understand it better.
https://jsfiddle.net/sahil_m03/jmk4rbp3/43/
I'm trying to figure out where there are any error(s). When the information is entered in the forms to the left and tab out of the input boxes after entering the information, it should update the field to the right (shopping cart).
However that is not happening and I'm not sure where I went wrong in the code. I did go through and fix quite a few errors on my end and any that showed up in my console. At this point I'm stuck.
JavaScript code:
"use strict";
window.addEventListener("load", function() {
// Calculate the shopping cart when the page loads
calcCart();
// Verify that the user has selected a session to attend
document.getElementById("regSubmit").click = sessionTest;
// Recalculate the shopping chart when any field loses the focus
document.getElementById("fnBox").blur = calcCart;
document.getElementById("lnBox").blur = calcCart;
document.getElementById("groupBox").blur = calcCart;
document.getElementById("mailBox").blur = calcCart;
document.getElementById("phoneBox").blur = calcCart;
document.getElementById("sessionBox").blur = calcCart;
document.getElementById("banquetBox").blur = calcCart;
document.getElementById("mediaCB").blur = calcCart;
});
// Function to verify that a session was selected by the user
function sessionTest() {
var confSession = document.getElementById("sessionBox")[i];
if (confSession.selectedIndex < 0) {
confSession.setValidity("Select a Session Package");
} else {
confSession.setValidity("");
}
}
// Function to calculate the shopping cart total
function calcCart() {
// Calculate the banquet cost for all guests
let guestCost = document.forms.register.elements.banquetGuests.value*55;
document.getElementById("regBanquet").textContent = document.forms.register.elements.banquetGuests.value;
// Determine the cost of the selected session
let sessionCost = 0; // Initial cost of the session
let sessionChoice = ""; // Initial chosen session
// Index of the chosen session
let selectedSession = document.forms.register.elements.sessionBox.selectedIndex;
// Retrieve the name and cost of the selected session
if (selectedSession.selected >= 0) {
sessionChoice = document.forms.register.elements.sessionBox[selectedSession].textContent;
sessionCost = document.forms.register.elements.sessionBox[selectedSession].value;
}
// Determine the cost of the media pack
let mediaCost = 0; // Initial media cost
let mediaChoice = ""; // Initial media choice
// If the user selects the media pack, update the choice and cost
if (document.forms.register.elements.mediaCB.checked === true) {
mediaChoice = "yes"
mediaCost = 115;
}
// Calculate total cost of the conference
// Multiply field values by 1 to convert them from text strings to numeric values
let totalCost = guestCost*1 + sessionCost*1 + mediaCost*1;
// Display the field values and calculated values in the Shopping Cart table
document.getElementById("regName").textContent = document.forms.register.elements.firstName.value + " " + document.forms.register.elements.lastName.value;
document.getElementById("regGroup").textContent = document.forms.register.elements.group.value;
document.getElementById("regEmail").textContent = document.forms.register.elements.email.value;
document.getElementById("regPhone").textContent = document.forms.register.elements.phoneNumber.value;
document.getElementById("regSession").textContent = sessionChoice.sel;
document.getElementById("regBanquet").textContent = document.forms.register.elements.banquetGuests.value;
document.getElementById("regPack").textContent = mediaChoice;
document.getElementById("regTotal").textContent = totalCost.toLocaleString("en-US", {style: "currency", currency: "USD"});
}
HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Hands-on Project 6-5</title>
<link rel="stylesheet" href="styles.css" />
<script src="project06-05.js" defer></script>
</head>
<body>
<header>
<h1>
Hands-on Project 6-5
</h1>
</header>
<article>
<section>
<h1>Registration Page</h1>
<form id="register" name="register" method="get" action="formsubmit.html">
<fieldset id="contactInfo">
<label for="fnBox">First Name*</label>
<input name="firstName" id="fnBox" type="text" required />
<label for="lnBox">Last Name*</label>
<input name="lastName" id="lnBox" type="text" required />
<label for="groupBox">Company or University</label>
<input name="group" id="groupBox" type="text" />
<label for="mailBox">E-mail*</label>
<input name="email" id="mailBox" type="email" required />
<label for="phoneBox">Phone Number*</label>
<input name="phoneNumber" id="phoneBox" type="tel" pattern="^\d{10}$|^(\(\d{3}\)\s*)?\d{3}[\s-]?\d{4}$"
required placeholder="(nnn) nnn-nnnn" />
</fieldset>
<fieldset id="confChoices">
<label for="sessionBox">Session Packs</label>
<select id="sessionBox" name="sessionOption" size="5" required>
<option value="95">Exhibits Only ($95)</option>
<option value="215">3 Session Pack ($215)</option>
<option value="420">6 Session Pack ($420)</option>
<option value="595">Session Pass ($595)</option>
<option value="845">VIP Pass ($845)</option>
</select>
<label for="banquet">MAS22 Banquet ($55 ea.)</label>
<input type="number" min="0" max="10" id="banquetBox" name="banquetGuests" /><span> attendees</span>
<label for="mediaPack">MAS22 Media Pack ($115)</label>
<input type="checkbox" name="mediaPack" id="mediaCB" value="115" />
</fieldset>
<input id="regSubmit" type="submit" value="continue" />
</form>
</section>
<aside id="reg1Aside">
<table>
<caption>Shopping Cart</caption>
<tr><th>Name</th><td><span id="regName"></span></td></tr>
<tr><th>Company</th><td><span id="regGroup"></span></td></tr>
<tr><th>E-mail</th><td><span id="regEmail"></span></td></tr>
<tr><th>Phone</th><td><span id="regPhone"></span></td></tr>
<tr><th>Session</th><td><span id="regSession"></span></td></tr>
<tr><th>Banquet Guests ($55 ea.)</th><td><span id="regBanquet"></span></td></tr>
<tr><th>Media Pack ($115)</th><td><span id="regPack"></span></td></tr>
<tr><th>TOTAL</th><td><span id="regTotal"></span></td></tr>
</table>
</aside>
</article>
</body>
</html>
Use .onchange onevent property or "change" event with .addEventListener(). Also, the <form> is wrapped around everything so you can use <output> instead of <span>. Also, everything now references the <form> via the HTMLFormElement interface, in which I saw that you were using but not to it's fullest extent:
const REG = document.forms.register;
const IO = REG.elements;
Removed .setValidity() since it wasn't really part of the question, and because it's not supported by Firefox. BTW, 99% of the time you should place all <script> right before the closing </body> tag. One small thing, you should make the phone number validation a little more relaxed, it's easier for the user to input: "123-456-7890" than it is to enter "(123) 456-789". Also, why do you want calcCart() to run at load? Do you have data the user entered previously?
The choice of tags are very semantic and the style (from what I see in the image) is slick. 👍
<!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, shrink-to-fit=no">
<title>Hands-on Project 6-5</title>
<style></style>
</head>
<body>
<header>
<h1>Hands-on Project 6-5</h1>
</header>
<main>
<form id="register" name="register" method="get" action="formsubmit.html">
<section>
<h2>Registration Page</h2>
<fieldset name="contactInfo" class='contactInfo'>
<legend>Contact Information</legend>
<label for="fnBox">First Name*</label>
<input id="fnBox" name="firstName" type="text" required />
<label for="lnBox">Last Name*</label>
<input id="lnBox" name="lastName" type="text" required />
<label for="groupBox">Company or University</label>
<input id="groupBox" name="group" type="text" />
<label for="mailBox">E-mail*</label>
<input id="mailBox" name="email" type="email" required />
<label for="phoneBox">Phone Number*</label>
<input id="phoneBox" name="phoneNumber" type="tel" pattern="^\d{10}$|^(\(\d{3}\)\s*)?\d{3}[\s-]?\d{4}$" required placeholder="(nnn) nnn-nnnn" />
</fieldset>
<fieldset name="confChoices" class='confChoices'>
<legend>Conference Choices</legend>
<label for="sessionBox">Session Packs</label>
<select id="sessionBox" name="sessionOption" required>
<option value="95">Exhibits Only ($95)</option>
<option value="215">3 Session Pack ($215)</option>
<option value="420">6 Session Pack ($420)</option>
<option value="595">Session Pass ($595)</option>
<option value="845">VIP Pass ($845)</option>
</select>
<label for="banquetBox">MAS22 Banquet ($55 ea.)</label>
<input id="banquetBox" name="banquetGuests" type="number" min="0" max="10" /><label for='banquetBox'> attendees</label>
<label for="mediaCB">MAS22 Media Pack ($115)</label>
<input id="mediaCB" name="mediaPack" type="checkbox" value="115" />
</fieldset>
<button>Continue</button>
</section>
<aside class="regSummary">
<table>
<caption>Registration Summary</caption>
<tr>
<th>Name</th>
<td><output id="regName"></output></td>
</tr>
<tr>
<th>Organization</th>
<td><output id="regGroup"></output></td>
</tr>
<tr>
<th>E-mail</th>
<td><output id="regEmail"></output></td>
</tr>
<tr>
<th>Phone</th>
<td><output id="regPhone"></output></td>
</tr>
<tr>
<th>Session</th>
<td><output id="regSession"></output></td>
</tr>
<tr>
<th>Banquet Guests ($55 ea.)</th>
<td><output id="regBanquet"></output></td>
</tr>
<tr>
<th>Media Pack ($115)</th>
<td><output id="regPack"></output></td>
</tr>
<tr>
<th>TOTAL</th>
<td><output id="regTotal"></output></td>
</tr>
</table>
</aside>
</form>
</main>
<script>
const REG = document.forms.register;
const IO = REG.elements;
window.addEventListener("load", function () {
/*
Recalculate the summary when any field data is entered and loses the focus
*/
IO.fnBox.onchange = calcCart;
IO.lnBox.onchange = calcCart;
IO.groupBox.onchange = calcCart;
IO.mailBox.onchange = calcCart;
IO.phoneBox.onchange = calcCart;
IO.sessionBox.onchange = calcCart;
IO.banquetBox.onchange = calcCart;
IO.mediaCB.onchange = calcCart;
});
// Function to calculate the summary total
function calcCart() {
// Calculate the banquet cost for all guests
let guestCost = +IO.banquetGuests.value * 55;
// Index of the chosen session
let selectedSession = IO.sessionBox.selectedIndex;
let sessionChoice = IO.sessionBox[selectedSession].text;
let sessionCost = +IO.sessionBox.value;
// If Media is checked
let mediaCost = IO.mediaCB.checked ? +IO.mediaCB.value : 0;
let mediaChoice = IO.mediaCB.checked ? "Yes" : "No";
// Calculate total cost of the conference
let totalCost = guestCost + sessionCost + mediaCost;
// Display the field values and calculated values in the Summary table
IO.regName.value = IO.firstName.value + " " + IO.lastName.value;
IO.regGroup.value = IO.group.value;
IO.regEmail.value = IO.mailBox.value;
IO.regPhone.value = IO.phoneBox.value;
IO.regSession.value = sessionChoice;
IO.regBanquet.value = IO.banquetBox.value;
IO.regPack.value = mediaChoice;
IO.regTotal.value = totalCost.toLocaleString("en-US", {
style: "currency",
currency: "USD"
});
}
</script>
</body>
</html>
you have added eventlistener 'load', this will be invoked after document loaded, can try 'change' or 'click' eventlisteners if you want data to be updated after input box change
The entire process of collecting data from the first input-field and shipping to second input-field2 is working perfectly but so that the value actually goes to the second input-field i must delete some letter from first input-field and re-enter some number so that the value actually goes to second-input.
Gif of doubt.
$(document).ready(function () {
$(function () {
var $cepAddressRouteTransporterGoogleMaps = $('#postal_code');
var $cepAddressRouteTransporter = $('#cepAddressRouteTransporter');
function onChange() {
$cepAddressRouteTransporter.val($cepAddressRouteTransporterGoogleMaps.val());
};
$('#postal_code')
.change(onChange)
.keyup(onChange);
});
});
First input represents this field postal_code & Second input represents this field cepAddressRouteTransporter.
<form action="transporter/route" method="post" role="form">
<table id="address">
<tr>
<td class="label">Zip code</td>
<td class="wideField">
<input class="field" id="postal_code" name="postal_code">
</td>
</tr>
</table>
<div class="input-field col s6">
<i class="material-icons prefix">directions</i>
<input placeholder="Ex: 18214-780" id="cepAddressRouteTransporter" name="cepAddressRouteTransporter" type="text" class="validate">
<label for="cepAddressRouteTransporter">CEP:</label>
</div>
</form>
Thanks for help!
you have to call your function onChange when the DOM is ready
onChange();
when you update the value, trigger the DOM event.
$('#postal_code').trigger('change');
$(function() {
var $cepAddressRouteTransporterGoogleMaps = $('#postal_code');
var $cepAddressRouteTransporter = $('#cepAddressRouteTransporter');
function onChange() {
$cepAddressRouteTransporter.val($cepAddressRouteTransporterGoogleMaps.val());
};
$('#postal_code').change(onChange).keyup(onChange);
// fire as soon as DOM is ready
onChange();
var t = window.setInterval(function(){
var n = Math.floor(Math.random() * 100000);
$('#postal_code').val(n);
// when you update the value, trigger the DOM event
$('#postal_code').trigger('change');
},1000);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<form action="transporter/route" method="post" role="form">
<table id="address">
<tr>
<td class="label">Zip code</td>
<td class="wideField">
<input class="field" id="postal_code" name="postal_code" value="90210">
</td>
</tr>
</table>
<div class="input-field col s6">
<i class="material-icons prefix">directions</i>
<input placeholder="Ex: 18214-780" id="cepAddressRouteTransporter" name="cepAddressRouteTransporter" type="text" class="validate">
<label for="cepAddressRouteTransporter">CEP:</label>
</div>
</form>
</body>
</html>
#code_monk Thanks for your help, i've reshaped your recommendation and add a few new things.
$(function () {
var $cepAddressRouteTransporterGoogleMaps = $('#postal_code');
var $cepAddressRouteTransporter = $('#cepAddressRouteTransporter');
function onChange() {
$cepAddressRouteTransporter.val($cepAddressRouteTransporterGoogleMaps.val());
};
$cepAddressRouteTransporterGoogleMaps.change(onChange).keyup(onChange);
$cepAddressRouteTransporter.change(onChange).keyup(onChange);
onChange();
var refresh = window.setInterval(function () {
$cepAddressRouteTransporter.val($cepAddressRouteTransporterGoogleMaps.val());
}, 3000);
});
Converting oclick() with addEventListener(), i have tried multiple times, But no Success. Can anyone help please. i have read in the book, that onlick() is not w3 standard, Any help will highly be aprreciated
Before with onclick() working Perfectly:
html code
<!DOCTYPE html>
<html>
<head>
<title>Splitting number</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form id="myForm" action="" name="myForm">
<table border="1">
<tr>
<td>Enter a phone number<br> [in the form (555) 555-5555]</td>
<td><input name="input" type="text" size="40"></td>
</tr>
<tr>
<td><input type="button" value="Split" onclick="parseNumber()"></td>
</tr>
<tr>
<td>Area code:</td>
<td><input name="areaCode" type="text" size="5"></td>
</tr>
<tr>
<td>Number:</td>
<td><input name="number" type="text" size="8"></td>
</tr>
</table>
</form>
</body>
</html>
javascript code:
function parseNumber() {
var myForm = document.getElementById( "myForm" );
myForm.areaCode.value = "";
myForm.number.value = "";
var completeNumber = myForm.input.value.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
myForm.areaCode.value = areaCode;
myForm.number.value = tokens2[0] + "-" + tokens2[1];
}
after, Not working:
html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Splitting number</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
Enter a phone number: in the form (555) 555-5555]
<input name="input" type="text" size="40" id="number" ><br>
<input type="button" value="Split" id="myBtn"><br><br>
Area code: <input name="areaCode" type="text" size="5" id="areaCode"><br>
Number: <input name="number" type="text" size="8" id="anotherNumber">
</body>
</html>
javascript code
var completeNumber = document.getElementById("number");
x = document.getElementById( "myBtn" );
function parseNumber() {
x.addEventListener("click", parseNumber);
completeNumber.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
document.getElementById("areaCode").innerHTML = areaCode.toString();
document.getElementById("anotherNumber").innerHTML = tokens2[0].toString() + "-" + tokens2[1].toString();
}
You need to add the event listener outside the function.
The listener is listening (clues in the name) for a mouse 'click' event on that element. When the event happens i.e you click on the element, it calls the function that it is assigned, in your case: parseNumber.
So since you are adding the event listener inside the function, it never gets added (as the function never gets called).
It should all work if you move the lines:
var x = document.getElementById( "myBtn" );
x.addEventListener("click", parseNumber);
outside the function. :)
I thnik no one actually read the question, if you already had a working example then changing onclick to eventListener is no problem:
var parseNum = document.getElementById('parse-number');
function parseNumber() {
var myForm = document.getElementById( "myForm" );
myForm.areaCode.value = "";
myForm.number.value = "";
var completeNumber = myForm.input.value.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
myForm.areaCode.value = areaCode;
myForm.number.value = tokens2[0] + "-" + tokens2[1];
}
parseNum.addEventListener("click", parseNumber);
<form id="myForm" action="" name="myForm">
<table border="1">
<tr>
<td>Enter a phone number<br> [in the form (555) 555-5555]</td>
<td><input name="input" type="text" size="40"></td>
</tr>
<tr>
<td><input type="button" value="Split" id="parse-number"></td>
</tr>
<tr>
<td>Area code:</td>
<td><input name="areaCode" type="text" size="5"></td>
</tr>
<tr>
<td>Number:</td>
<td><input name="number" type="text" size="8"></td>
</tr>
</table>
</form>
Change your code to this where eventListener is added outside the bounded function. Otherwise it will repeatedly bind an eventListener to the button.
Also place your script.js on the bottom of the HTML page. Because when the script executed the DOM element is not found since the DOM is not rendered at the script execution time.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Splitting number</title>
</head>
<body>
Enter a phone number: in the form (555) 555-5555]
<input name="input" type="text" size="40" id="number" ><br>
<input type="button" value="Split" id="myBtn"><br><br>
Area code: <input name="areaCode" type="text" size="5" id="areaCode"><br>
Number: <input name="number" type="text" size="8" id="anotherNumber">
<script type="text/javascript" src="script.js"></script>
</body>
</html>
JavaScript
var completeNumber = document.getElementById("number");
var x = document.getElementById( "myBtn" );
function parseNumber() {
completeNumber.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
document.getElementById("areaCode").innerHTML = areaCode.toString();
document.getElementById("anotherNumber").innerHTML = tokens2[0].toString() + "-" + tokens2[1].toString();
}
x.addEventListener("click", parseNumber);
I have two buttons in my form for calling two JavaScript functions. The first button works good in its onclick event calling the payroll() function successfully but the second button is of type submit and it never calls the send() function on form submission. I don't know why this issue occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html >
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript" >
function payroll() {
var basic=document.forms["salary"]["bsalary"].value;
var empid=document.forms["salary"]["empid"].value;
var ta,hra,da,pf,netsalary,grosssalary;
if (empid == ""||basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if(isNaN(basic))
{alert("Salary must be in Numbers");
return false;
}
hra=basic*40/100;
da=basic*15/100;
pf=basic*12/100;
basic=parseInt(basic);
hra=parseInt(hra);
da=parseInt(da);
grosssalary=basic + hra + da;
ta=basic*6.2/100;
netsalary=grosssalary-ta;
document.getElementById("hra").innerHTML=hra;
document.getElementById("ta").innerHTML=ta;
document.getElementById("da").innerHTML=da;
document.getElementById("netsalary").innerHTML=netsalary;
document.getElementById("pf").innerHTML=pf;
document.getElementById("grosssalary").innerHTML=grosssalary;
window.alert("HI"+grosssalary);
return true;
}
function send()
{
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.forms['salary']['hra'].value;
var da = document.forms['salary']['da'].value;
var ta = document.forms['salary']['ta'].value;
var pf = document.forms['salary']['pf'].value;
var gross_sal = document.forms['salary']['grosssalary'].value;
window.alert("HI"+gross_sal);
var net_sal = document.forms['salary']['netsalary'].value;
Sijax.request('send',[id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%" >
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return send()" >
<label id = "empid">Employee ID</label><br>
<input type = "text" name = "empid" placeholder = "Employee ID" /><br><br>
<label id = "bsalary">Basic Salary</label><br>
<input type = "text" name = "bsalary" placeholder = "Basic salary" /><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for ="hra">House Rent Allowance(HRA)</label>
<p id="hra" name="hra"></p><br>
<label for ="ta">Travel Allowance(TA)</label>
<p id="ta" name="ta"></p><br>
<label for ="da"> Dearness Allowance(DA)</label>
<p id="da" name="da"></p><br>
<label for ="netsalary">Net Salary</label>
<p id="netsalary" name="netsalary"></p><br>
<label for ="pf">Provident Fund(PF)</label>
<p id="pf" name ="pf"></p><br>
<label for ="grosssalary">Gross Salary</label>
<p id="grosssalary" name="grosssalary"></p><br><br>
<input type="submit" value="Upload Salary">
</form>
</div>
</body>
</html>
You can't act with <p> elements like as a form-elements. You may create a respective <input type="hidden"> elements and fill them in payroll(), or get values by .innerHtml on paragraphs.
P.S. You have actually a TypeError exception, calling undeclared form elements like document.forms['salary']['grosssalary'] and so on.
okay, quick fix, since you are using python flask library Sijax for ajax and therefore jQuery, you can alter your javascript send function like this:
function send(e){
e.preventDefault(); //it is as good as returning
//false from the function in all cases
var id = document.forms['salary']['empid'].value;
...
}
and change your onsubmit handler declaration like this:
<form id="salary" name="salary" style="margin-top: 2%" method="post"
onsubmit="return send(event)" >
please note that when you stop the event chain propagation, you will have to do a manual submission of the form.
So, you can modify your send function to do .preventDefault based on your custom criterias, otherwise, let the form submit
Your code actually works, if you're running this code as a snippet here in stack overflow, Form submission is actually blocked by default. Try running your code in codepen. I tried it and it's actually working.
http://codepen.io/jhonix22/pen/VPZagb
Check this out. It is nowhere close to a perfect solution but I think it helps. You can not access the paragraphs as if you would the form input elements. Im not entirely sure what Sijax thing is. I believe it is just a normal AJAX HTTP thing with some sort of CSRF security filters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{
{
g.sijax.get_js() | safe
}
}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript">
function payroll() {
var basic = document.forms["salary"]["bsalary"].value;
var empid = document.forms["salary"]["empid"].value;
var ta, hra, da, pf, netsalary, grosssalary;
if (empid == "" || basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if (isNaN(basic)) {
alert("Salary must be in Numbers");
return false;
}
hra = basic * 40 / 100;
da = basic * 15 / 100;
pf = basic * 12 / 100;
basic = parseInt(basic);
hra = parseInt(hra);
da = parseInt(da);
grosssalary = basic + hra + da;
ta = basic * 6.2 / 100;
netsalary = grosssalary - ta;
document.getElementById("hra").innerHTML = hra;
document.getElementById("ta").innerHTML = ta;
document.getElementById("da").innerHTML = da;
document.getElementById("netsalary").innerHTML = netsalary;
document.getElementById("pf").innerHTML = pf;
document.getElementById("grosssalary").innerHTML = grosssalary;
window.alert("HI" + grosssalary);
return true;
}
function send() {
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.getElementById('hra').innerHTML;
var da = document.getElementById('da').innerHTML;
var ta = document.getElementById('ta').innerHTML;
var pf = document.getElementById('pf').innerHTML;
var gross_sal = document.getElementById('grosssalary').innerHTML;
window.alert("HI" + gross_sal);
var net_sal = document.getElementById('netsalary').innerHTML;
// I think you are missing something here.
Sijax.request('send', [id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%">
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return false">
<label id="empid">Employee ID</label><br>
<input type="text" name="empid" placeholder="Employee ID"/><br><br>
<label id="bsalary">Basic Salary</label><br>
<input type="text" name="bsalary" placeholder="Basic salary"/><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for="hra">House Rent Allowance(HRA)</label><br>
<p id="hra" readonly name="hra"></p>
<label for="ta">Travel Allowance(TA)</label><br>
<p id="ta" readonly name="ta"></p>
<label for="da"> Dearness Allowance(DA)</label><br>
<p id="da" readonly name="da"></p>
<label for="netsalary">Net Salary</label><br>
<p id="netsalary" readonly name="netsalary"></p>
<label for="pf">Provident Fund(PF)</label><br>
<p id="pf" readonly name="pf"></p>
<label for="grosssalary">Gross Salary</label><br>
<p id="grosssalary" readonly name="grosssalary"></p><br>
<input type="button" onclick="send()" value="Upload Salary">
</form>
</div>
</body>
</html>