Cannot read property 'value' of null - javascript

I have spent probably an hour attempting to get this figured out... I keep getting this error no matter what I try:
Cannot read property 'value' of null
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 101 Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<h1>Hello, world!</h1>
<div id="login_box"><form class="form-inline" action="JavaScript: login();" method="post">
<input type="text" class="input-small" id="login_username" name="username" placeholder="Username">
<input type="password" class="input-small" id="login_password" name="password" placeholder="Password">
<label class="checkbox"><input type="checkbox" id="login_autologin" name="autologin"> Remember me </label>
<button type="submit" class="btn" name="login">Sign in</button>
</form></div>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/overall_js.js"></script>
</body>
</html>
and the related JS file (overall_js.js):
function login() {
$("#login_box").html("logging you in....");
console.log(document.getElementById("login_username").value);
$.post("user.php?mode=login", {
username : document.getElementById("login_username").value,
password : document.getElementById("login_password").value,
autologin : document.getElementById("login_autologin").value,
}).done(function(data) {
result = JSON.parse(data);
if (result.status == 3) {
$("#login_box").html(
"Welcome back, " + result.user_row.username + "!");
} else {
$("#login_box")
.html("You was not logged in: , " + result.error_msg);
}
});
}
Thanks if you can figure this out! I am also new to jQuery and JS so if anyone has any suggestions to make it more "Standard", any tips are appreciated!

This line
$("#login_box").html("logging you in....");
replaces the content of your <div>. You remove the form and all input elements...

See corrections needed below, lines 6 and 7:
function login() {
$("#login_box").append("logging you in....");
var u = $('#login_username').val();
var p = $('#login_password').val();
var al = $('#login_autologin').is(':checked');
console.log(u, p, al);
$.post("user.php?mode=login", {
username : u,
password : p,
autologin : al,
}).done(function(data) {
result = JSON.parse(data);
if (result.status == 3) {
$("#login_box").html(
"Welcome back, " + result.user_row.username + "!");
} else {
$("#login_box")
.html("You was not logged in: , " + result.error_msg);
}
});
}

Related

How do you make a submit button redirect to another page after the user has inputted the correct password?

could you please help me find out what's wrong? After login, it is supposed to redirect you to another page, but nothing happens. The user name is: Joshua and the password is: Joshua#123.
<html>
<head>
<title>Login: MessengerX</title>
<link rel="stylesheet" type="text/css" href="C:\Users\Tania\Documents\Website\style.css">
<meta charset="UTF-8">
<meta name="description" content="HTML website called MessengerX. Send messages to anyone who has logged in.">
<meta name="author" content="Joshua Hurley">
<meta name="keywords" content="HTML, MessengerX, Joshua Hurley, Website, Supremefilms">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript">
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "Joshua" && password == "Joshua#123") {
alert("Login successfully");
location.replace("www.youtube.com"); // Redirecting to other page.
} else {
attempt--; // Decrementing by one.
alert("You have " + attempt + " attempt left;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
</script>
<script src="js/login.js"></script>
</head>
<body>
<div class="imgcontainer">
<img src="C:\Users\Tania\Documents\Website\Screenshots\face.jpg" height="500" alt="Avatar" class="avatar">
</div>
<div class="container">
<div class="main">
<h1 style="color:"><b><i>Login: MessengerX</i></b></h1>
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" name="username" id="username" />
<label>Password :</label>
<input type="password" name="password" id="password" />
<button type="submit" value="Login" id="submit" onclick="validate()" />
</form>
<b><i>Submit</i></b>
</div>
</div>
</body>
</html>
Try this:
window.location.replace("https://www.youtube.com")
You can move code inside window.addEventListener('load' or you can move script after dom at the end
Suggestion: use the entire URL with HTTP or HTTPS.
location.replace("https://www.youtube.com");
<script type="text/javascript">
window.addEventListener('load', (event) => {
var attempt = 3; // Variable to count number of attempts.
/// code here
});
</script>
As leonardofmed mentioned, better place your script just befor </body> closing tag,
because you need to load html first, so script can see elements, otherwise at it's start there is no elements yet, so this will cause error, as for redirecting you can use:
// Simulate a mouse click:
window.location.href = "http://www.w3schools.com";
// Simulate an HTTP redirect:
window.location.replace("http://www.w3schools.com");
use <form><button type="button" ... instead
<form><button type="submit" ... has its own logic ("magic"), which is doing the problem.
use protocol in url location.replace("https://www.youtube.com"), otherwise it's relative path
BTW never validate password on client!!!

Auto-format html input type tel

I have a problem with add auto Spaced in Input Tel.
I would like to add a 9-digit number so that every 3 digits take a break (spaces or pauses) like +880 111 222 333. Someone could explain how to achieve it?
function addSpace(){
var inputValue = document.getElementById("telInput").value;
var inputValueLength = inputValue.length;
if(inputValueLength == 3 || inputValueLength == 7){
document.getElementById("telInput").value = inputValue+" ";
}
}
<input type="tel" id="telInput" onkeypress="addSpace()">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="GET">
<input type="tel" name="phone" id="phone" pattern="[0-9 -+()]{11,11}">
<input type="submit" value="Submit" >
</form>
</body>
</html>
<script>
let itemInput=document.querySelector('input[type=tel]') ;
itemInput.addEventListener('keypress',phone);
function phone()
{
let p=this.value;
if((p.length+1)%4==0 && p.length<9) this.value=p+" ";
}
</script>
XXX XXX XXX only accepts numbers that are 0-9 in this view.try one.
<!DOCTYPE html>
<html>
<head>
<script>
function inNumber(elm){
if (!elm.value) return
elm.value = elm.value.replace(/ /g, '')
}
function withSpaces(elm) {
if (!elm.value|| isNaN(elm.value) || elm.value.length < 3) return
elm.value = elm.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");;
}
</script>
</head>
<body>
<p>Enter any number value and press tab </p>
<input id="0" onblur="withSpaces(this)" onfocus="inNumber(this)">
</body>
</html>
JQuery:
<input type="tel" placeholder="123-456-7890" maxlength="12" id="phone" >
<script>
jQuery(document).ready(function() {
$("#phone").keyup(function() {
var number = $(this).val();
var lngth = number.length;
if (lngth == 3 || lngth == 7) {
$("#phone").val(number + "-") ;
} else if (lngth >12 ) {
$("#phone").val(number.slice(0,12));
}
})
});
</script>
Maybe maxlength="12" and else if (lngth >12 ) is redundant but it doesn't hurt either

How to get form input using jQuery?

Instead of PHP, I want to use jQuery to get user input and pass in a function and update a "div".
My HTML(includes scripts) code is:
<head>
<title>Mobile Locale test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content="Mobile Locale this is!" />
<script>
var x;
$(document).ready(function()
{
x = $("#q").val();
var name = "Hello " + x + ". Welcome to this site";
$("#test").text(name);
});
console.log(x);
</script>
</head>
<body>
<form>
<input type="text" id="q" placeholder="Your name please...">
<button id="submit">Submit!</button>
<div id="test">This should change...</div>
</form>
</body>
What I want:
I want to get input from user and assign that input to x.
Then I want to complete a string and pass x in that string.
Then I want to write that complete sentence in div id="test".
I am stumbling this for more than 6 hours but got no success. Tried numerous codes but failed.
Referred w3schools jQuery form example but they are using form method="abcd.asp".
Thanks in advance...
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jquery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var x;
$(document).ready(function()
{
var x = $("input#q").val();
var name = "Hello " + x + ". Welcome to this site";
$("#test").text(name);
});
function CallSubmit()
{
var x = $("input#q").val();
var name = "Hello " + x + ". Welcome to this site";
$("#test").text(name);
return false;
}
</script>
</head>
<body>
<form>
<input type="text" id="q" placeholder="Your name please...">
<button id="submit" onclick="return CallSubmit();">Submit!</button>
<div id="test">This should change...</div>
</form>
</body>
</html>
Your script is executed on page load, when the input is empty - call the code on an event, like keyup
$(document).ready(function(){
$("#q").keyup(function() {
var name = "Hello " + this.value + ". Welcome to this site";
$("#test").text(name);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="q" placeholder="Your name please...">
<button id="submit">Submit!</button>
<div id="test">This should change...</div>
You could get the name in the click event of the button.
Working example : http://jsfiddle.net/jjjoeupp/
$('#submit').on('click', function()
{
x = $("#q").val();
var name = "Hello " + x + ". Welcome to this site";
$("#test").text(name);
});
Hope it helps!!!
You can bind the focusoutevent with the input to dynamically change the div. Another approach would be to update on each keypress.
$(document).ready(function () {
$('#q').keypress(function (event) {
if (event.which == 13) {
event.preventDefault();
if ($(this).val() != '') {
var x = $(this).val();
var name = "Your string " + x;
}
$('#test').text(name);
}
});
});
fiddle : http://jsfiddle.net/86evwkbx/

changePage is undefined

I am trying to build a simple app on phonegap and when i run the code i get an error in logcat as "Uncaught TypeError: Cannot call method 'changePage' of undefined". Here is my index.html and main.js. I am getting that error in the function of main.js.
index.html
<!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.1.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="main.js"></script>
<style>
body
{
background-color:#d0e4fe;
}
h1
{
color:Red;
text-align:center;
}
</style>
</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>
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"
$("#loginPage").live("pageinit", function(e) {
checkPreAuth();
});
</script>
</body>
</html>
main.js is here :
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 = "bidray";
var str2 = "fivestars123";
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");
}
The problem is with the last line of the main.js. The changePage is not getting defined.
Any help would be appreciated.
Thanks.

Get error in browser console when usimg python server

I get this error while running an html file which contains a form. It is supposed to move to another screen after login.
GET http://mdsad.com/p.js?v=1373144857354
I cannot understand where I am going wrong in the code. It doesn't even enter the function that is called.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/stackmob-js-0.9.1-bundled-min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Pocket Docket</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function nextpage() {
alert("function");
StackMob.init({
publicKey: "my_key",
apiVersion: 0
});
var u = document.getElementById('username').value;
var p = document.getElementById('password').value;
alert(u);
alert(p);
var user = new StackMob.User({
username: u,
password: p
});
user.login(false, {
success: function(model, result, options) {
alert("Success");
alert("Success");
window.open('newp1.html');
StackMob.isUserLoggedIn(u, {
yes: function() {
alert("Logged In!");
},
no: function() {
alert("Login Error!");
}
});
},
error: function(model, result, options) {
console.log(result);
alert("Login Error!");
}
});
};
</script>
</head>
<body>
<div id="topPan">
<div id="topHeaderPan"></div>
<div id="toprightPan"></div>
</div>
<div id="bodyPan">
<div id="bodyleftPan">
<h2>Pocket Docket</h2>
<p class="greentext">For Every Salesman</p>
<p>Pocket Docket is a means to simplify the working of the sales
department in a company.</p>
<p>For every salesperson, it is like a manager, assigning tasks and
recording progress, updating it on their profiles. Easier to manage,
higher the productivity.</p>
</div>
<div id="bodyrightPan">
<div id="loginPan">
<h2>Pocket Docket <span>login</span></h2>
<form action="" method="post">
<label>Login ID</label><input id="email" name="email" type=
"text"> <label>Password</label><input id="pass" name="pass"
type="password"> <input class="button" name="Input" onclick=
"nextpage()" type="submit" value="Login">
</form>
<ul>
<li class="nonregister">Forgot Password ?</li>
<li class="register">
Click Here
</li>
</ul>
</div>
<div id="loginBottomPan">
</div>
</div>
</div>
</body>
</html>
The error is in download.js (some file i don't know in the browser console).
Please tell me where is the error.
I figure out what was wrong with your code:
var u = document.getElementById('username').value;
var p = document.getElementById('password').value;
where your input Id's are 'email' and 'pass'
so change the above lines to :
var u = document.getElementById('email').value;
var p = document.getElementById('pass').value;
also
it's better to close "input" markup
Hope it works now.

Categories

Resources