External JavaScript file is unresponsive for form validation - javascript

I am creating an html file that links to an external JavaScript file to validate a form in my html file. Every time I hit "Submit" on my form, the page is simply re-loaded and no JavaScript is performed. I have already tried Chrome and Firefox, plus I have disabled pop-up blocking as well as ensuring JavaScript is enabled.
As far as I can tell so far, my JavaScript file is not being reached, since the first line of the single function in my JavaScript file has a call to alert(), and no pop-up or dialog windows are appearing.
My HTML, CSS, and JavaScript files are all uploaded to the same directory, and the html file is successfully linking with the CSS file because my style changes are clearly apparent.
Why won't my JavaScript file be reached?
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta name="viewport" content="width=device-width" charset="utf-8" />
<title>TitleLine</title>
<link rel="stylesheet" href="Style.css"/>
<script type="text/JavaScript" src="checkTheForm.js" >
</script>
</head>
<body>
<form name="form1" id="form1" method="post" action="" onsubmit="return validate()">
<fieldset>
<legend>Survey</legend>
<label>Name: </label>
<input type="text" name="name" id="name"/>
<input type="submit" />
<input type="reset" />
</fieldset>
</form>
</body>
</html>
JavaScript:
function validate()
{
var myDay = new Date();
var locMyDay = myDay.toLocaleDateString();
alert("testing");
console.log("hi");
if(document.forms["form1"]["name"].value == "")
{
alert("Name field is blank - please enter a name.");
document.getElementById("name").focus();
document.getElementById("name").style.backgroundColor = "#FF0000";
return false;
}
else
{
document.getElementById("name").style.backgroundColor = "#FFFFFF";
}
else
{
alert("Form successfully submitted at: " + locMyDay);
return true;
}
}

Related

Render a new page in JS after a form submit

I am new to Javascript (like I really know nothing) and I have to program a Picross game for my school. My teachers gave me an HTML home page for the game and I can't touch it. This page has a form with action pointing on itself but with parameters on the URL. Here is the code :
<!doctype html>
<html>
<head>
<title>Picross editor & player</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="picross.css" type="text/css">
<script src="picross.js"></script>
</head>
<body>
<nav>
<section>
<h2>Create a grid</h2>
<form action="picross.html" method="get">
<input type="hidden" name="edit">
<table>
<tr><td>Lignes :</td><td><input type="number" name="lines" value="10" min="5" max="20"></td></tr>
<tr><td>Colonnes :</td><td><input type="number" name="cols" value="10" min="5" max="20"></td></tr>
</table>
<input type="submit" value="Create !">
</form>
</section>
</nav>
</body>
</html>
My job is to only work on picross.js and I have no idea how to render a blank page (or a grid) if the form has been submitted because when I try to detect the submit, the HTML page renders just after my catch. I also have to do it on the same page, when no parameters are given it's the home page from my teachers but when the form is submitted, the game opens in the same picross.html but with ?lines=x&cols=y or something like this. Here is what I've tried :
window.onload = function() {
var form = document.querySelector("form");
form.onsubmit = submitted.bind(form);
}
function submitted(e) {
console.log("catch");
console.log(e);
}
This writes catch in the console for a tenth of a sencond and then the HTML renders just after. So what I'm looking for is when the form is submitted, the JS code should render a grid (or a blank page, I can work on the grid later) to play the picross game.
Thank for your help
JavaScript is really easy and fun, you can always google anything you want to make and/or learn in javascript/html or any web technology.
As I understood from your question, you want to open a new window when the button is clicked, so to do that you have to first turn off the default behavior of the form, and to do that you can use the parameter e that passed in the event callback submitted.
JavaScript events
e.preventDefault()
This will prevent the page from reloading.
Next, to open a new window, you can use window object.
Window object.
window.open(....)
Full example:
window.onload = function() {
var form = document.querySelector("form");
form.onsubmit = submitted.bind(form);
}
function submitted(e) {
e.preventDefault();
console.log("catch");
var myWindow = window.open("", "Yaay", "width=200,height=100");
myWindow.document.write("<p>Peace begins with a smile</p>");
}
<!doctype html>
<html>
<head>
<title>Picross editor & player</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="picross.css" type="text/css">
<script src="picross.js"></script>
</head>
<body>
<nav>
<section>
<h2>Create a grid</h2>
<form action="picross.html" method="get">
<input type="hidden" name="edit">
<table>
<tr><td>Lignes :</td><td><input type="number" name="lines" value="10" min="5" max="20"></td></tr>
<tr><td>Colonnes :</td><td><input type="number" name="cols" value="10" min="5" max="20"></td></tr>
</table>
<input type="submit" value="Create !">
</form>
</section>
</nav>
</body>
</html>
I hope I explained clearly.
Note: Run code snippet might not work, because popups are not allowed.

How to disable HTML/JavaScript form if JavaScript is disabled in browser

First off the bat I am new to this an really trying my best to understand how this works. I have the following simple login form that leads to a homepage if the right login credentials are submitted. However when run in Firefox with JavaScript disabled the login credentials are ignored and my homepage is displayed anyway no matter what login details I provide. I have created a message in between <noscript></noscript> which fires when JavaScript is disabled. What I would like to achieve is that the warning message displays only and that the form etc. is disabled and not displayed until the login page is reloaded with JavaScript enabled. Can someone please help me with this? It is much appreciated!! My code is
<!doctype html>
<!-- This is is the main start page saved in index.html -->
<html lang="en-US">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Login details</h2>
<noscript>
<h3>Before you login</h3>
<p>JavaScript needs to run for this site to work properly.<br />
Please activate JavaScript in your browser<br />
and reload this page to login.
</p>
</noscript>
<form id="myForm" name="login" onsubmit="return validateFormOnSubmit()" action="http://localhost:8080/index.html" method="post">
<fieldset>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>
<script>
function validateFormOnSubmit() {
var un = document.login.username.value;
var pw = document.login.password.value;
var username = "username"
var password = "password"
if ((un == username) && (pw == password)) {
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>
You can achieve this without adding extra JavaScript. You can use a <noscript> tag also in the <head>, so you are able to hide this with CSS:
…
<head>
…
<noscript>
<style>
#myForm {
display: none
}
</style>
</noscript>
</head>
…

I want to hide the form and show a written success message as well as reload the page with a hash value

I'm working on a form and as I submit I want to hide the form and show a written success message when I submit it. I want to also be able to reload the page with a hash value.
I made this function, which works but I feel like it'll give me some reload problems as the form appearing again and success message dissapearing. The form tag contains the onSubmit="submissionmMessage()
<script>
function submissionMessage() {
window.location.hash = "#success";
document.getElementById("successMessage").style.display = 'block';
document.getElementById("form").style.display = 'none';
</script>
<div>
<p style="display:none;" id="successMessage"><strong> Success!</strong></p>
</div>
It works for hiding the showing the message but I feel like there could be room for errors?
also if I put in the "window.location.hash = "#success"
and the success url as the url with the #sucess at the end will it be counter-intuitive?
Sample Code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#success {
display: none;
}
</style>
</head>
<body>
<p id="demo" class="font-effect-shadow-multiple"></p>
<script>
function submissionmMessage() {
/*
Get Response from SERVER using AJAX.
*/
document.getElementById("success").style.display = "block";
}
</script>
<div id="success">Your Form has bee Submitted.</div>
<form id="form" method="POST" action="#" onsubmit="event.preventDefault(); submissionmMessage();">
<input type="text" name="txt" id="txt" />
<input type="submit" name="submit" />
</form>
</body>
</html>

In Sinatra, how do I make a multi-page pop-under form which stays on the same page as you fill it out?

I've made a form that appears in a pop-under window, but I can't figure out how to make it multi-step.
Here's my code:
1) main.rb file:
[
'rubygems',
'sinatra',
'sequel'
].each{|g| require g}
DB = Sequel.sqlite('database.sqlite')
DB.create_table? :data_table do
primary_key :id
varchar :img_path
varchar :form1_name
varchar :form2_option
end
before do
#img_path = nil
#form1_name = nil
#form2_option = nil
end
get '/?' do
erb :index
end
post '/form2' do
user_img = params['user_img']
#img_path = './public/images/uploads/' + user_img[:filename]
File.open(#img_path,'wb'){|f| f.write(user_img[:tempfile].read)}# Copying the upload file to the server directory
#form1_name = params['form1_name'] # !!!DATAPOINT!!!
end
2) layout.erb file
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Multi-page form test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <!-- jQuery UI CSS -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> <!-- jQuery -->
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <!-- jQuery UI -->
<script src="./js/script.js"></script>
</head>
<body>
<%= yield %>
</body>
3) index.erb file
<button id="upload_form_opener" type="button">Click here to upload</button>
<div id="upload_form_container" title="Form container title">
<form action="form2" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<img id="upload_preview" style="width: 300px; height: 300px;" />
<input id="upload_image" accept="image/*" type="file" name="user_img" onchange="PreviewImage();" />
<script type="text/javascript">
// This JavaScript snipppet is for previewing the image upload
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("upload_image").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("upload_preview").src = oFREvent.target.result;
// document.getElementById("upload_image").disabled = true
}; // DONE: function (oFREvent)
}; // DONE: function PreviewImage()
</script>
<p>Name <input type="text" name="form1_name" /></p>
<input type="submit" value="Next" />
</form>
</div>
4) script.js
$(document).ready(function(){
var uFormContainer = $('#upload_form_container');
// This snippet is for opening the pop-under form
uFormContainer.dialog({autoOpen: false});
$('#upload_form_opener').click(function(){
uFormContainer.dialog('open');
});
});
5) I want the second step of the form to look like this...
<form action="form2" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<p>Some other text field <input type="text" name="form2_option" /></p>
<input type="submit" value="Next" />
</form>
...but I don't want to leave the page (which is '/', as far as Sinatra is concerned). Is this possible in Sinatra?
There are multiple ways to implement this:
Save some cookie or session, which step is now, and depends on that yield different forms. After submitting write next step id into session and redirect to root_url.
Use ajax to send form and render next step's form.
You can even not really send form, but just switch to next, just hidding previous fields with javascript and show next step's fields. After submitting all parameters will be sent.

Lotus Xpages Extension library and page submission

Step1: Added two input texts and a Button with save document server-side action to the xpage. By clicking on the button it saves the document.
Step 2. Set up one of the input texts as a dijit.form.ValidationTextBox. This automatically adds the '**parseOnLoad: true**' parameter to the page. The source of the page in the browser:
Step 3. Add the **required=true** parameter to the dijit.form.ValidationTextBox. The document still can be saved even the validationTextBox left empty.
Step 4. Add a numberspinner item from the Lotus Extension library to the xpage. This adds the **dojoType="dijit.form.Form"** attribute to the page and this prevents document save, if the inputvalidationtextbox is empty.
Step 4. Add a numberspinner item from the Lotus Extension library to the xpage. This adds the dojoType="dijit.form.Form" attribute to the page and this prevents document save, if the inputvalidationtextbox is empty. The source of the page in the browser:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="hu">
<head>
<script type="text/javascript">if(!navigator.cookieEnabled)window.location.href='http://localhost/development/Labor/labor.nsf/test1.xsp?SessionID=D937UTFGVR';</script>
<title></title>
<link rel="stylesheet" type="text/css" href="/xsp/.ibmxspres/.mini/css/#Da&#Ib&2Tfxsp.css&2TfxspLTR.css&2TfxspFF.css.css">
<script type="text/javascript" src="/xsp/.ibmxspres/dojoroot-1.6.1/dojo/dojo.js" djConfig="locale: 'hu-hu', parseOnLoad: true"></script>
<script type="text/javascript" src="/xsp/.ibmxspres/.mini/dojo/.hu-hu/#Fi&#Fo&#Iq.js"></script>
</head>
<body class="xspView tundra">
<form id="view:_id1" method="post" action="/development/Labor/labor.nsf/test1.xsp" class="xspForm" enctype="multipart/form-data" dojoType="dijit.form.Form">
<input type="text" dojoType="dijit.form.ValidationTextBox" required="true" id="view:_id1:inputText1" name="view:_id1:inputText1" class="xspInputFieldEditBox"><button class="xspButtonCommand" type="button" name="view:_id1:button1" id="view:_id1:button1">Label</button><br>
<input type="text" id="view:_id1:inputText2" name="view:_id1:inputText2" class="xspInputFieldEditBox"><input dojoType="dijit.form.NumberSpinner" id="view:_id1:djNumberSpinner1" name="view:_id1:djNumberSpinner1">
<input type="hidden" name="$$viewid" id="view:_id1__VUID" value="!d937utjhyk!">
<input type="hidden" name="$$xspsubmitid">
<input type="hidden" name="$$xspexecid">
<input type="hidden" name="$$xspsubmitvalue">
<input type="hidden" name="$$xspsubmitscroll">
<input type="hidden" name="view:_id1" value="view:_id1"></form>
<script type="text/javascript">
XSP.addOnLoad(function() {
XSP.attachEvent("view:_id1:_id2", "view:_id1:button1", "onclick", null, true, 2);
});
</script>
</body>
</html>
My question is how to add a partial refresh, or submit function to the xpage, which can be executed, even empty required field. This is possible, until I add the dijit.form.NumberSpinner from the Extension Library.
<form id="view:_id1"
method="post"
action="/development/Labor/labor.nsf/test1.xsp"
class="xspForm" enctype="multipart/form-data"
dojoType="dijit.form.Form">
<script type="dojo/method" event="submit">
if(!this.validate()) {
dojo.xhrPost({ url: form.get("action"), content: form.getValues() }).then(
function() { /* successor */ },
function() { /* errorhandle */ }
);
}
else {
this.containerNode.submit();
}
</script>
<!-- ... -->
</form>

Categories

Resources