I am a grade 11 level computer programmer and encountered some difficulties when trying to complete our JSON assignment. The goal is to save an object to local storage, but my html and js do not do so. Instead, nothing happens at all. All feedback is appreciated.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript" src="JDOS.js">
</script>
<title>Announcements Storage</title>
</head>
<body>
<form>
<fieldset>
<legend>Add New Announcement</legend>
Title:<br>
<input required id="title" type="text"><br>
Category:<br>
<input required id="category" type ="text"><br>
Creator:<br>
<input required id="creator" type="text"><br>
Type:
<select required id='type' name="type" >
<option value="Event">Event</option>
<option value="Reminder">Reminder</option>
<option value="General">General</option>
</select><br>
Date and Time:<br>
<input required id="date" type="date"><br>
<input required id="time" type="time"><br>
Sex:<br>
<select required id='sex'>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="All">All</option>
</select><br>
Grade:<br>
<input required id='grade' type='text'><br>
Message:<br>
<textarea required id="message" rows="10" cols="50">Type
announcement here</textarea><br>
<input type="submit" onclick="createAnnouncement()" value="Post">
</fieldset>
</form>
<div id="showAnnouncement"></div>
</body>
</html>
Javascript begins here:
function createAnnouncement() {
var title= document.getElementById('title').value;
var category= document.getElementById('category').value;
var creator= document.getElementById('creator').value;
var type= document.getElementById('type').value;
var datetime= document.getElementById('datetime').value;
var sex= document.getElementById('sex').value;
var grade= document.getElementById('grade').value;
var message= document.getElementById('message').value;
var announcement = {
Title: title,
Category: category,
Creator: creator,
Type: type,
DateTime: datetime,
Sex: sex,
Grade: grade,
Message: message
};
var x = JSON.stringify(announcement);
localStorage.setItem('announcement', x);
}
function showAnnouncement(){
var obj = localStorage.getItem('announcement').value;
var obj2 = JSON.parse (obj);
document.getElementById('showAnnouncement').innerHTML = "title:" + obj2.title
+ "category:" + obj2.category + "creator:" + obj2.creator + "type:" +
obj2.type + "datetime:" + obj2.datetime + "sex:" + obj2.sex + "grade:" +
obj2.grade + "message:" + obj2.message;
}
You have some errors on your logic here.
Since your input is created as type="submit", it will try to do a HTTP POST instead of calling your createAnnouncement() function. You can change it to type="button".
After that, you need to find a way to trigger the showAnnouncement() function, this could be an element such as an <a> or another <button>.
Related
firebase.auth().onAuthStateChanged(function(user) {
console.log(user);
if (user) {
var user_id = user.uid;
firebase.database().ref('Clients/'+user_id)
.once('value').then(function(snapshot){
snapshot.forEach(function(childSnapshot) {
var client_name = childSnapshot.child("client_name").val();
var client_phone = childSnapshot.child("client_phone").val();
var client_address = childSnapshot.child("client_address").val();
var total = client_name + "<br>" + client_phone + "<br>" + client_address;
console.log(total);
$('.client_option').append('<option>' + total +'</option');
});
})
}
else{
window.location.href="{% url 'login' %}";
}
});
In this code, I already got individual client information. I have 3 input fields. As these values are displayed as options, I want that, when the user selects a set of options(client_name, phone, address), the individual info passes to specific fields. Here are my input fields.
<input type="text" class="form-control" id="clientName" list="client"
autocomplete="off">
<datalist class="form-control client_option" id="client" hidden>
</datalist>
<input type="tel" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}" id="phone"
class="form-control" autocomplete="off">
<input type="text" class="form-control" id="address" autocomplete="off">
Thanks in advance.
function disp(){
var client_name = $('#client_name').val();
var client_phone = $('#client_phone').val();
var client_address = $('#client_address').val();
var total = client_name + "-" + client_phone + "-" + client_address;
$('.client_option').append('<option>' + total +'</option');
}
$(document).on("change", ".client_option", function(){
var valArr = $(".client_option option:selected").text().split("-");
$("#clientName").val(valArr[0]);
$("#phone").val(valArr[1]);
$("#address").val(valArr[2]);
$("#client").append("<option>" + $(".client_option option:selected").text() + "</option>");
});
<input id="client_name"> </input>
<input id="client_phone"> </input>
<input id="client_address"> </input>
<button type="submit" onclick="disp()">Submit</button>
<select class="client_option"><option>Please Select</option></select>
<input type="text" class="form-control" id="clientName" list="client"
autocomplete="off">
<datalist class="form-control client_option" id="client" hidden>
</datalist>
<input type="tel" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}" id="phone"
class="form-control" autocomplete="off">
<input type="text" class="form-control" id="address" autocomplete="off">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try this out to make this example I have replaced the childSnapshopt.child but it should work as same.
The big point is you can use text() to insert the text into an element.
I also suggest that you use template strings to build your string. Then there is no need of the string concat.
function disp(){
var client_name = $('#client_name').val();
var client_phone = $('#client_phone').val();
var client_address = $('#client_address').val();
var total = `${client_name} \n${client_phone} \n${client_address}`
console.log(total);
$('.client_option').text('<option>' + total +'</option');
}
<input id="client_name"> </input>
<input id="client_phone"> </input>
<input id="client_address"> </input>
<button type="submit" onclick="disp()"></button>
<div class=".client_option"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Please let me know why this doesn't work and how I can achieve this as simple as possible. my professor wants the simplicity to reflect 15 minutes or work. I just don't grasp it though. Thanks in advance!
<script language="JavaScript">
var obj = {
name = "",
address = "",
ccNumber = "",
}
function printObj() {
document.getElementById("display").innerHTML = obj.name + " " + obj.address + " " + obj.ccNumber;
}
function storeInput(user_input1, user_input2, user_input3) {
name = document.getElementById("myObject").form.user_input1;
address = document.getElementById("myObject").form.user_input2;
ccNumber = document.getElementById("myObject").form.user_input3;
}
</script>
<form>
<label><b>Enter full name</b></label>
<input type="text" name="message" id="user_input1">
</form>
<form>
<label><b>Enter billing address</b></label>
<input type="text" name="message" id="user_input2">
</form>
<form>
<label><b>Enter CC number</b></label>
<input type="text" name="message" id="user_input3">
</form>
<input type="submit" onclick="obj.storeInput(user_input1, user_input2, user_input3);obj.showInput()"><br />
<p id='display'></p>
Ok! You need your storeInput() to reference the declared object. Currently with your code as it is storeInput() is an independent function but for you event handler (onclick) to work. You need to redefine the storeInput() as
obj.storeInput() = function(user_input1, user_input2, user_input3) {.....};
This will get the job done. It will not store the values, but will display them.
<!DOCTYPE html>
<html>
<body>
<form>
<label><b>Enter full name</b></label>
<input type="text" name="message" id="user_input1">
<label><b>Enter billing address</b></label>
<input type="text" name="message" id="user_input2">
<label><b>Enter CC number</b></label>
<input type="text" name="message" id="user_input3">
</form>
<input type="submit" onclick="aFunction();"><br />
<p id='display'></p>
<script>
function aFunction(){
var x = document.querySelector('#user_input1').value; // gets value of user_input1 field
var y = document.querySelector('#user_input2').value; // gets value of user_input2 field
var z = document.querySelector('#user_input3').value; // gets value of user_input3 field
document.querySelector('#display').innerHTML = x + ' ' + y + ' ' + z; // puts the values in <p> with id of 'display'
}
</script>
</body>
</html>
Hope this helps you understand.
I keep on getting this error Uncaught ReferenceError: calculatePrice is not defined at HTMLInputElement.onclick.
I have already seen the other answers on here regarding this error and none of them worked. I tried defining the script in body or head, didn't make a difference. I also think the function and button I connect it to are correct as I compared to a solution, so I really don't know why it is not working when I press it.
<html>
<head>
<link href="style/myStyles.css" type="text/css" rel="stylesheet">
<title> The Printing Company </title>
</head>
<body>
<script type="text/javascript"></script>
<script>
function calculatePrice() {
var quantity, type, price
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic"){
price = 10*(quantity/100);
} else if (type.includes("Medium"){
price = 15*(quantity/100);
} else if (type.includes("High"){
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
</script>
<form action="form.php" method="post">
<label >Company Name</label><br>
<input name="name" type="text" required /><br>
<br>
<label>Contact email</label><br>
<input name="email" type="email" required /><br>
<br>
<label>Business Card type</label><br>
<select name="cardstype" id="cardstype">
<option value="" disabled selected>-Select Card Quality-</option>
<option value="Basic Quality">Basic Quality</option>
<option value="Medium Quality">Medium Quality</option>
<option value="High Quality">High Quality</option>
</select><br>
<br>
<label>Business Cards quantity</label><br>
<input name="qty" id ="qty" type="number" required Onchange = '
if( !( this.value >= 100 && this.value <= 1000 ) ) {
//alert the user that they have made a mistake
alert( this.value + " is not a valid quantity. Minimun quantity per order: 100 and maximum: 1000.");
this.value=""; //clears the text box
}'><br>
<br>
<input type="button" name="Price" value="Calculate Price" onclick="calculatePrice()"/>
<input type="submit" value="Submit Order"/>
</form>
</html>
Can anyone help?
I think You are missing the closing parentheses in your if statements:
if (type.includes("Basic") {
^^^ here
Working example:
function calculatePrice() {
var quantity, type, price;
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic")) {
price = 10*(quantity/100);
} else if (type.includes("Medium")) {
price = 15*(quantity/100);
} else if (type.includes("High")) {
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
<form action="form.php" method="post">
<label >Company Name</label><br>
<input name="name" type="text" required /><br>
<br>
<label>Contact email</label><br>
<input name="email" type="email" required /><br>
<br>
<label>Business Card type</label><br>
<select name="cardstype" id="cardstype">
<option value="" disabled selected>-Select Card Quality-</option>
<option value="Basic Quality">Basic Quality</option>
<option value="Medium Quality">Medium Quality</option>
<option value="High Quality">High Quality</option>
</select><br>
<br>
<label>Business Cards quantity</label><br>
<input name="qty" id ="qty" type="number" required Onchange = '
if( !( this.value >= 100 && this.value <= 1000 ) ) {
//alert the user that they have made a mistake
alert( this.value + " is not a valid quantity. Minimun quantity per order: 100 and maximum: 1000.");
this.value=""; //clears the text box
}'><br>
<br>
<input type="button" name="Price" value="Calculate Price" onclick="calculatePrice(event)"/>
<input type="submit" value="Submit Order"/>
</form>
You have a few typos in your function:
Missing closing curly brace (looks fixed now)
Missing semicolon after variable definition: var quantity, type, price;
Mismatched parentheses in if/elseif conditions (3 times): if (type.includes("Basic")) {
The below code has these problems fixed:
<script>
function calculatePrice() {
var quantity, type, price;
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic")){
price = 10*(quantity/100);
} else if (type.includes("Medium")){
price = 15*(quantity/100);
} else if (type.includes("High")){
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
</script>
Therefore, the function calculatePrice isn't defined and can't be called.
I'm trying to make a form which when I click the submit button will send the information from the form fields to a javascript function and then show the results to the user. I've made something like this before that's very similar and works fine, but for some reason this isn't doing anything when I click submit. I must have missed something. Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" >
<title>Javascript Form</title>
</head>
<body>
<form id="formID" name="myform" action="" method="get">
Customer Name:
<input type="text" name="names" value="">
<br/>
Street Address:
<input type="text" name="street" value="">
<br/>
City:
<input type="text" name="city" value="">
<br/>
State:
<input type="text" name="state" value="">
<br/>
Zip Code:
<input type="text" name="zip" value="">
<br/>
Beginning Odometer Reading:
<input type="text" name="beginO" value="">
<br/>
Ending Odometer Reading:
<input type="text" name="edinO" value="">
<br/>
Number of Days Car was Used:
<input type="text" name="days" value="">
<br/>
<input type="button" name="button" value="Submit" onClick="car(this.form)">
</form>
<script type="text/javascript">
function car(form) {
var names = form.names.value;
var street = form.street.value;
var city = form.city.value;
var state = form.state.value;
var zip = form.zip.value;
var beginO = form.beginO.value;
var endO = form.endO.value;
var days = form.days.value;
var miles = endO - beginO;
var charge = days * 15 + miles * 0.12;
alert("Miles driven: " + miles + ". Charge: " + charge + ". Name: " + names + ". Address : " + street + " , " + city + " " + state + " " + zip + ". ");
}
</script>
</body>
</html>
It's because you have a JavaScript error at this line:
var endO = form.endO.value;
You have a typo in your form element name:
<input type="text" name="edinO" value="">
form.endO is undefined, so getting value throws an error.
I have a JavaScript cookie question. I have used the example for writing and reading a JavaScript cookie from this site: http://www.tutorialspoint.com/javascript/javascript_cookies.htm. The cookie reads and writes just fine to the same page but once I go to another page with a similar form that it should work in - the information in the cookie is gone.
I had originally gotten this to work off my desktop but once I added it to the DEV site we are testing on - it only works on one page. Basically I can set a cookie on one page with a form and then on another page there will be no cookie to read. However I can create another cookie on the second form and it saves just fine. When I go back to page one form - the first cookie I created populates the form fields.
So:
Form 1 page - cookie 1 created
- then go to -
Form 2 page - cookie 1 doesn't exist but I can create cookie 2
- then go to -
Form 1 page - cookie 1 loads into form 1
- then go to -
Form 2 page - cookie 2 loads into form 2
Additional information about the website:
Apache server
PHP 5.4
AngularJS 1.2.26
Webservice
other JavaScript and jQuery files
3rd party scripts
About the only thing I see in the document.cookie when I debug it is a phpsessid. Could this be blocking my cookies from being carried over the form on the other page? These forms are all on the same domain, so...
The desktop version which is the same as the DEV website:
Page 1
<html>
<head>
<script src="tutorialspoint-cookies.js" type="text/javascript"></script>
</head>
<body>
<h1>FORM 1</h1>
<form name="form_000c" id="form_000c" action="">
<label>First Name:</label>
<input type="text" name="First_Name" id="First_Name" /><br />
<label>Last Name:</label>
<input type="text" name="Last_Name" id="Last_Name" /><br />
<label>Email:</label>
<input type="text" name="Email" id="Email" /><br />
<label>Phone Number:</label>
<input type="text" name="Phone" id="Phone" /><br />
<label>Timeline:</label>
<select name="Timeline" id="Timeline">
<option value="time1">Timeline 1</option>
<option value="time2">Timeline 2</option>
<option value="time3">Timeline 3</option>
<option value="time4">Timeline 4</option>
</select><br />
<label>Measurements:</label>
<select name="Measurements" id="Measurements">
<option value="meas1">Measurement 1</option>
<option value="meas2">Measurement 2</option>
<option value="meas3">Measurement 3</option>
<option value="meas4">Measurement 4</option>
</select><br />
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
go to page 2
</body>
</html>
Page 2
<html>
<head>
<script src="tutorialspoint-cookies.js" type="text/javascript"></script>
</head>
<body onLoad="ReadCookie()">
<h1>FORM 2</h1>
<form name="form_000c" id="form_000c" action="">
<label>First Name:</label>
<input type="text" name="First_Name" id="First_Name" /><br />
<label>Last Name:</label>
<input type="text" name="Last_Name" id="Last_Name" /><br />
<label>Email:</label>
<input type="text" name="Email" id="Email" /><br />
<label>Phone Number:</label>
<input type="text" name="Phone" id="Phone" /><br />
<label>Timeline:</label>
<select name="Timeline" id="Timeline">
<option value="time1">Timeline 1</option>
<option value="time2">Timeline 2</option>
<option value="time3">Timeline 3</option>
<option value="time4">Timeline 4</option>
</select><br />
<label>Measurements:</label>
<select name="Measurements" id="Measurements">
<option value="meas1">Measurement 1</option>
<option value="meas2">Measurement 2</option>
<option value="meas3">Measurement 3</option>
<option value="meas4">Measurement 4</option>
</select><br />
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
go to page 1
</body>
</html>
JavaScript cookie
<!--http://www.tutorialspoint.com/javascript/javascript_cookies.htm
function WriteCookie(){
cookievalue1 = escape(document.form_000c.First_Name.value) + ";";
cookievalue2 = escape(document.form_000c.Last_Name.value) + ";";
cookievalue3 = escape(document.form_000c.Email.value) + ";";
cookievalue4 = escape(document.form_000c.Phone.value) + ";";
cookievalue5 = escape(document.form_000c.Timeline.value) + ";";
cookievalue6 = escape(document.form_000c.Measurements.value) + ";";
document.cookie = "First_Name=" + cookievalue1;
document.cookie = "Last_Name=" + cookievalue2;
document.cookie = "Email=" + cookievalue3;
document.cookie = "Phone=" + cookievalue4;
document.cookie = "Timeline=" + cookievalue5;
document.cookie = "Measurements=" + cookievalue6;
alert("Setting Cookies : " + "First_Name=" + cookievalue1 + "Last_Name=" + cookievalue2 + "Email=" + cookievalue3 + "Phone=" + cookievalue4 + "Timeline=" + cookievalue5 + "Measurements=" + cookievalue6 );
}
function ReadCookie(){
var allcookies = document.cookie;
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
// the cookie is leaving a white space in the name so we need to remove it with .trim()
name = name.trim();
value = cookiearray[i].split('=')[1];
document.getElementById(name).value = value;
}
}
When you are setting cookie, it is important to remember that you need to specify path also.
// use path=/ while setting cookie in javascript
document.cookie = "First_Name=" + cookievalue1 + " path=/";
document.cookie = "Last_Name=" + cookievalue2 + " path=/";
document.cookie = "Email=" + cookievalue3 + " path=/";
document.cookie = "Phone=" + cookievalue4 + " path=/";
document.cookie = "Timeline=" + cookievalue5 + " path=/";
document.cookie = "Measurements=" + cookievalue6 + " path=/";
It's an old question, but still pop as a first link, so I would like to share my observation.
Answer above is perfectly fine, but you should not forget to use the delimiter between options.
Cookies have several options, many of them are important and should be
set. The options are listed after key=value, delimited by ;
javascript info
So it should look like this:
document.cookie = "First_Name=" + cookievalue1 + "; path=/";
document.cookie = "Last_Name=" + cookievalue2 + "; path=/";