scope of array (array refreshes with page refresh) - javascript

I have this code:
application.js
var userArray = [];
$(document).ready(function() {
$("#signupform").submit(function(e) {
var user = {
name: $('#pname').val(),
email: $('#email').val()
};
userArray.push(user);
var html = new EJS({url: 'templates/usershow.ejs'}).render(user);
var content = document.getElementById('content');
content.innerHTML = content.innerHTML + html;
$("#signupform").remove();
e.preventDefault();
});
});
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>it IT</title>
<link rel="stylesheet" type="text/css" href="application.css" />
<script src="jquery.js"></script>
<script src="application.js"></script>
<script type="text/javascript" src="ejs_production.js"></script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>it IT</h1>
<div id="signup">
<form id="signupform">
Name: <input type="text" name="pname" id="pname"><br>
Email: <input type="text" name="email" id="email"><br>
<input type="submit" value="sign up">
</form>
</div>
<div id="signin"></div>
<div id="content"><h2>Name : Email</h2></div>
</body>
</html>
templates/usershow.ejs
<ul>
<li><%= userArray[userArray.length - 1].name %> - <%= userArray[userArray.length - 1].email %></li>
</ul>
In the js file, I have declared an array outside of the function. I am trying to push the user to the array from within the function. All goes well until I refresh the page...the array gets refreshed too - I'm a newb, but it seems like a scope problem. I'm trying to keep the array intact, even after a page refresh - so I can refer to it at other points in the file. Any help would be appreciated. Also, does anyone have a good link to where I could read about creating sessions (for sign in/sign out) in javascript?

Related

Templates in Ractive.js

I am new to Ractive.js and just playing around with it. I am trying to build a simple app, but strangely, it's not working on my pc and I am getting an error in console "Could not find template element with id #template", where #template refers to the id assigned to script tag. Nothing gets rendered on my browser. However, the same code is running fine in JSFiddle. Can someone explain what is happening here?
Here is the fiddle.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Weather Details</title>
<meta name="description" content="Get weather for your city">
<link href="https://fonts.googleapis.com/css?family=Arimo" rel="stylesheet">
<link rel="stylesheet" href="weather.css">
<script src='https://cdn.ractivejs.org/latest/ractive.js'></script>
<script src="weather.js"></script>
</head>
<body>
<div id="main" class="page-container">
<script id='template' type='text/ractive'>
<div class="weather-widget">
<div class="input-group">
<label>City Name</label>
<input type="text" class="form-control" placeholder="Enter City Name" />
</div>
<div class="input-group">
<label>Recent Searches</label>
<select>
<option>Select from recent searches</option>
</select>
</div>
<div class="weather-details">
<table>
<tbody>
<tr>
<th>Wind</th>
<td>{{country}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</script>
</div>
</body>
</html>
Code in weather.js:
var ractive = new Ractive({
el: '#main',
template: '#template',
data: {
country: 'London'
}
});
At the time weather.js executes, the element hasn't yet been created. You could either move the <script src='weather.js'></script> tag to the bottom of the page (inside <body>, after the topmost <div> containing the template element the script refers to), or add a defer attribute: <script defer src='weather.js'></script>.

Why is parseInt not working for me?

No matter what I try I get NAN when I try to parse an input value into a variable. I am trying to make a calculator to determine fuel economy.
<!DOCTYPE html>
<html>
<head>
<title>Fuel Calculator</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="Demo project">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<style type="text/css"></style>
</head>
<body>
<div class="wrapper">
<h1>Fuel Usage</h1>
<div class="row">
<div class="col-md-12">
<form>
<div class="form-group">
<label>Miles Driven Per Year</label>
<input type="text" class="form-control" id="mpy">
</div>
<div class="form-group">
<label>MPG</label>
<input type="text" class="form-control" id="mpg">
</div>
<p>Gallons Used: <span id="used"></span</p>
<div class="form-group">
</div>
<button id="submit" type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
js file
var mpy = parseInt($('#mpy').val(), 10);
var mpg = parseInt($('#mpg').val(), 10);
var gallonsUsed = mpy/mpg;
$('#submit').click(function(){
$('#used').text(gallonsUsed);
});
Since you have the input fields declared globally, the initial value in the text value is empty. So the result of parseInt would give you a NAN value.
You need to calculate the parsed values once you invoke the click event.
$('#submit').click(function(e){
var mpy = parseInt($('#mpy').val(), 10);
var mpg = parseInt($('#mpg').val(), 10);
var gallonsUsed = mpy/mpg;
$('#used').text(gallonsUsed);
});
Working example : https://jsfiddle.net/DinoMyte/b9bhs4s3/
The way you have your code, mpy/mpg/gallonsUsed are all calculated when the page is loaded (before any user input can even take place)
Your code would make more sense like this
$('#submit').click(function(){
var mpy = parseInt($('#mpy').val(), 10);
var mpg = parseInt($('#mpg').val(), 10);
var gallonsUsed = mpy/mpg;
$('#used').text(gallonsUsed);
});
So that the calculation is done once user has entered data and hit submit

Submitting html form in php

This is my first.php page html part. I have a form including a div and a submit button. I want when button clicked, open a new page (second.php) and display contents of div(id=orderList)
<form id="orderForm" action="second.php">
<div class="col-md-5" id="orderList">
<h3 align="center">Sipariş Listesi</h3>
</div>
<div>
<button type="submit" id="firstConfirmButton" class="btn btn-primary btn-lg">Onayla</button>
</div>
</form>
This is javascript part;
$("#orderForm").submit(function() {
var content = $('#orderList').html();
console.log(content); //(no problem everything is ok)
$('#confirmForm').val(content);
var content2 = $('#confirmForm').html();
console.log(content2); //(it is null)
});
And this is second.php where I want to display the contents in the div(id=confirmForm)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="script.js"></script>
<META name=viewport content="width=1024, initial-scale=1">
<META http-equiv="Content-Type" content="text/html; charset=utf-8" />
<META HTTP-EQUIV="Content-language" CONTENT="tr">
<link href="shift.css" rel="stylesheet">
<link rel="stylesheet" href="bootstrap.css">
<link rel="stylesheet" href="product.css">
</head>
<body>
<div id="confirmForm"> </div>
</body>
</html>
It doesn't work, what should I change?
If $('#confirmForm') is not an input item you cant access it using $('#confirmForm').val();
your Form is missing method attribute, add POST in method by default its GET
<form id="orderForm" method="post" action="second.php">
Add a <textarea> in first.php inside orderForm to hold the content of #ordelist using jquery and in second page you can get it using $_POST['confirmForm'];
<textarea name="confirmForm" id="confirmForm" cols="30" rows="10"></textarea>
in second page you do this
<div id="confirmForm"> <?php echo $_POST['confirmForm'] ?> </div>
You're trying to put the content in #confirmForm, which isn't present in the first file.
There is no need for JavaScript here. Grab the content of the div using $_['post']
Try this its working :
first.php
<html>
<head>
</head>
<form id="orderForm" action="second.php">
<div class="col-md-5" id="orderList">
<textarea name="confirmForm" id="confirmForm" cols="30" rows="10">Sipari Listesi</textarea>
</div>
<div>
<button type="submit" id="firstConfirmButton" class="btn btn-primary btn-lg">Onayla</button>
</div>
</form>
</html>
second.php
<html>
<body>
<?php
echo $_REQUEST[confirmForm];
?>
</body>
</html>
In addition to what Saqueib said, I think you'll need to make a jQuery change too. I think you're looking for the html() method, not val() because it looks like you're trying to change the displayed HTML, right?

uncaught type error: undefined is not a function

Im making a simple form with Telerik Appbuilder HTML5 + javascript that takes a users input and logs it to the console when they click the submit button.
ClientClass.js:
function Client() {
this.username = "username",
this.password = "Password",
this.printUsername = function() {
this.username=$("#Username").val()
console.log(this.username);
};
};
Home.html:
<div data-role="view" data-title="Login" data-layout="main" data-model="APP.models.login">
<script src="../scripts/ClientClass.js"></script>
<h1 data-bind="html: title"></h1>
<script src="../scripts/ClientClass.js"></script>
<script>
function printUsername() {
var client = new client();
client.printUsername();
}
</script>
<ul data-role="listview" data-style="inset">
<li>
<label>Username
<input type="text" value="" id="Username" />
</label>
</li>
<li>
<label>Password
<input type="password" value="" />
</label>
</li>
<li>
<label>
<button onclick="printUsername()" type="button">Submit</button>
</label>
</li>
</ul>
</div>
Index.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="kendo/styles/kendo.mobile.all.min.css" rel="stylesheet" />
<link href="styles/main.css" rel="stylesheet" />
<script src="cordova.js"></script>
<script src="kendo/js/jquery.min.js"></script>
<script src="kendo/js/kendo.mobile.min.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/ClientClass.js"></script>
</head>
<body>
<script src="scripts/ClientClass.js"></script>
<script src="scripts/ClientClass.js"></script>
<div data-role="layout" data-id="main">
<div data-role="header">
<div data-role="navbar">
<span data-role="view-title"></span>
</div>
</div>
<!-- application views will be rendered here -->
<label>
<input type="password" value="password" />
</label>
<div data-role="footer">
<div data-role="tabstrip">
Home
Settings
Contacts
</div>
</div>
</div>
</body>
</html>
It says in the console:
uncaught type error: undefined is not a function.
Then it says it is at index.html#views/home.html:1 and when I click that and it takes me to sources panel of the debugger. And it says the source is index.html and it says:
(function() {with (this[2]) {with (this[1]) {with (this[0]) {return function(event) {printUsername() }; }}}})
Does anyone see any issues with my html or javascript? Or the way I import the script? Thanks
you are declaring your client as an object, not as a "class". So using new on your object doesn't make quite sense.
So it's up to you or you keep your object and simply remove:
var client = new client();
or you use a class
function Client(){}

how to solve the error " Uncaught TypeError: Cannot call method 'changePage' of undefined"

I am just a beginner in phonegap as well as in javascript so while making a simple app for example, i wrote the following code in the index.html head and my main.js file is not getting included while i run the code. I hope anyone could help me out with the problem.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo</title>
<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0rc2.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script>
<script src="jquery.mobile/jquery.mobile-1.0rc2.js"></script>
<script type="text/javascript" charset="utf-8" src="assests/www/main.js"></script>
</head>
<body onload="init()">
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Welcome to Phonegap</h1>
</div>
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
<script>
$("#loginPage").live("pageinit", function(e) {
checkPreAuth();
});
</script>
</body>
</html>
here is the main.js file code as well.I just want only a particular login id to be valid.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
navigator.notification.alert("You entered a username and password");
handleLogin();
}
}
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
$("#submitButton",form).attr("disabled","disabled");
var u = $("#username", form).val();
var p = $("#password", form).val();
var str1 = "burden123";
var str2 = "game1234";
var n1 = str1.localeCompare(u);
var n2 = str1.localeCompare(p);
if(u != '' && p!= '') {
$.post("http://www.coldfusionjedi.com/demos/2011/nov/10/service.cfc? method=login&returnformat=json", {username:u,password:p}, function(res) {
if(n1==0 && n2==0) {
$.mobile.changePage("some.html");
} else {
navigator.notification.alert("Your login failed", function() {});
}
$("#submitButton").removeAttr("disabled");
},"json");
} else {
navigator.notification.alert("You must enter a username and password", function() {});
$("#submitButton").removeAttr("disabled");
}
return false;
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginPage");
}
<script type="text/javascript" charset="utf-8" src="assests/www/main.js"></script>
this line in your code should be changed to
<script type="text/javascript" charset="utf-8" src="main.js"></script>
as main js is in same folder of index.html page.
<script type="text/javascript" charset="utf-8" src="assests/www/main.js"></script>
in above check you path in src also try putting it above and place a alert at top in main.js
check if all scripts above this is including or not.
Thanks

Categories