Why won't the form value show up? - javascript

I am creating a simple form, and I want to write to the console the value of the input once the form has been submitted and successfully validated. However, when I go to test my current progress, I input a random piece of text and nothing shows up, even in the console. Here is the code I have now (excluding any commented out code):
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script language="Javascript">
window.onload = function() { // So the DOM can be defined
function validateForm() {
var form = document.forms['encrypt']['text'];
if(form == "") {
alert("Enter piece of text to encrypt");
return false;
} else {
console.log(form.value);
}
}
}
</script>
</head>
<body>
<form name="encrypt" action="#" onsubmit="return validateForm()">
Text: <input type="text" name="text">
<input type="submit" name="Submit and Encrypt!">
</form>
</body>
</html>
Even when I type nothing and submit the form, the alert doesn't pop up. There was other posts related to form problems, but they don't have any relation to mine. Is there something wrong with my code? What is the problem and how can I fix it?
Edit: I realized window.onload only executes the code inside of it when the window is loading. After that, all functions cease to exist. In addition to removing the onload handler, I had to relocate the validation function within the body.

Your validateForm function is only visible within your onload function. Additionally, you were comparing the form to an empty string, not the value within the text field in the form. The console.log would also not have been visible, because the page refreshes before you can see it.
Below is the code with those three things fixed.
<html>
<head>
<meta charset="utf-8" />
<script>
function validateForm() {
var text = document.forms['encrypt']['text'].value;
if(text == "") {
alert("Enter piece of text to encrypt");
return false;
} else {
alert("Entered '" + text + "', refreshing now.");
return true;
}
}
</script>
</head>
<body>
<form name="encrypt" action="#" onsubmit="return validateForm()">
Text: <input type="text" name="text">
<input type="submit" name="Submit and Encrypt!">
</form>
</body>
</html>

There's no reason to wrap this function in an onload event handler. And doing so is limiting the scope of the function definition so that the code which tries to call it can't actually see it. (That is, after onload completes, the function you defined is no longer in scope and ceases to exist.)
Just remove the handler and define the function directly:
<script language="Javascript">
function validateForm() {
var form = document.forms['encrypt']['text'];
if(form == "") {
alert("Enter piece of text to encrypt");
return false;
} else {
console.log(form.value);
}
}
</script>

The problem is your function validateForm() is not accessible in the scope when you click the submit. You can verify this by call this function in the console.
In your code, it's defined inside the window.onload, so please move the function out of it.

Try to remove window.onload = function() { and just keep the validateForm function.

Related

I'm trying to make a specific input into a text area call a specific javascript function, but it won't work

So to give a little bit of detail, I'm trying to make an interactive fiction game or text adventure. I have a form where all the "commands" for the game will be typed. I'm working on the first command which is the string "start" to call a prompt. Just to test the code, I have the prompt say "success!" when done correctly. What's happening though, is as soon as I open the web browser to test, the prompt triggers before I even type a command. Here's the code.
<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>
<form id="testForm"> <input type="text" name="">
</form>
</body>
</html>
And then here's the javascript.
var input = document.getElementById("testForm");
if (input = "start") {
prompt("Success!");
}
Try this:
<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>
<form id="testForm">
<input type="text" id="myInput">
</form>
<script>
var myForm = document.getElementById("testForm");// get the form element.
var myInput = document.getElementById("myInput");// get the input element
myForm.onsubmit = function() { // when the form is submitted, execute this function.
if (myInput.value == "start") { // if the value of the input equals 'start', show prompt.
prompt("Success!");
}
return false; //return false, so the form doesn't get submitted.
};
</script>
</body>
</html>
Edit:
Added submit event handler, that returns false, so the form does not get submitted.
You need to check the value of the input like so
var input = document.getElementById("inputID");
var value = input.value;
The code will always be ran straight away because it has no event handler. You could add a button which triggers it
document.getElementById('button').addEventListener('click', function () {
var input = document.getElementById("inputID");
if (input.value === 'start') {
// Do something
}
});
Or if you prefer on the forms submit event:
document.getElementById('testForm').addEventListener('submit', function () {
var input = document.getElementById("inputID");
if (input.value === 'start') {
// Do something
}
});

IE Onblur and focus issue

I am trying to show alert and focus on control when user try to leave control without entering any value in the control. This requirement is something like user is forced to enter values (I know there are certain limitations of such requirements).
When user leaves textbox1 alert is shown and at the sametime alert for textbox2 is also displayed as I am trying to focus on textbox1. This becomes infinite loop in IE and both the pop up keep on displaying in IE.
This code works perfectly in chrome but not in any version of ie.
Code sniphet below:
<html>
<head>
<script language="javascript">
function ShowAlertAndFocus1(){
var txt1 = document.getElementById("txtBox1");
if(txt1.value.length == 0){
alert("Blur 1 called");
txt1.focus();
};
};
function ShowAlertAndFocus2(){
var txt2 = document.getElementById("txtBox2");
if(txt2.value.length == 0){
alert("Blur 2 called");
txt2.focus();
};
};
</script>
</head>
<body>
<input type="text" id = "txtBox1" onblur="ShowAlertAndFocus1();"/>
<input type="text" id = "txtBox2" onblur="ShowAlertAndFocus2();"/>
</body>
</html>
I am not sure if am missing something or this limitation is with IE only?
<!DOCTYPE html>
<html>
<head>
<title> x </title>
<script>
function setOnBlur( txtBox,n ){
setTimeout( function(){
if (document.activeElement==txtBox) {
txtBox.onblur=function(){
if (txtBox.value.length == 0){
alert("Blur "+n+" called")
setTimeout( function(){txtBox.focus()},0 )
}
else txtBox.onblur=null
}
}
},0)
}
</script>
</head>
<body>
<input type=text id=txtBox1 onfocus=setOnBlur(txtBox1,1) >
<input type=text id=txtBox2 onfocus=setOnBlur(txtBox2,2) >
</body>
</html>
No Proper Solutions found till now.
EDIT -
Trick - I used two variables and set them inside the methods. I again checked the values before showing the popup.
Basically, your alerts cause the focus to go away as soon as you focus on the text fields. It is an odd behavior in IE that the blur event comes first. Maybe you can try replacing the alerts and try using console.log instead (That would only work in IE 8 & 9 if developer tools are opened). Or best, you can remove the alerts completely. That should work.
<html>
<head>
<script language="javascript">
function ShowAlertAndFocus1(){
var txt1 = document.getElementById("txtBox1");
if(txt1.value.length == 0){
console.log("Blur 1 called");
txt1.focus();
};
};
function ShowAlertAndFocus2(){
var txt2 = document.getElementById("txtBox2");
if(txt2.value.length == 0){
console.log("Blur 2 called");
txt2.focus();
};
};
</script>
</head>
<body>
<input type="text" id = "txtBox1" onblur="ShowAlertAndFocus1();"/>
<input type="text" id = "txtBox2" onblur="ShowAlertAndFocus2();"/>
</body>
</html>

How change HTML document after false onsubmit without manual page reloading

I want to change HTML document elements when the onsubmit event handler returns false.
Inside function validate() a cookie is set (BTW, is there simpler way than cookie?).
Onload event handler checkIfFalseSubmit() checks cookie and runs function changeDocument() that changes document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>How change document after false onsubmit without manual page reloading</title>
<script type="text/javascript">
function validate() {
// http://www.javascripter.net/faq/settinga.htm
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 1000*5000);
document.cookie = "cookie1=a; expires=" + expire.toGMTString();
alert ("Always false - just for testing");
return false;
}
function changeDocument() {
myDiv.innerHTML = "Form validation failed";
}
// http://stackoverflow.com/questions/10730362/javascript-get-cookie-by-name
function getCookie(name) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function checkIfFalseSubmit() {
if ( getCookie("cookie1") == "a")
changeDocument();
}
</script>
</head>
<body onload="checkIfFalseSubmit()">
<div id="myDiv">Before Submit</div>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" name="f" onsubmit="return validate();" >
<input type="text" name="myName" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Problem is that onload happens only when I manually reload page.
Without reloading the alert is shown but the document remains unchanged.
Is there another event that I should use instead of onload for my purpose?
Is there another way to get my goal?
I think it is overly convoluted. You don't have to use cookies and and body onload event. Just keep validate() called on form submit and changeDocument() to display your message.
Inside of validate() if validation failed call changeDocument() before returning false.

jquery, alert when trying to submit empty field in form

I'm sure I must have missed something really obvious, but can't for the life of me see what it is.
I have the below javascript, that (in theory) looks at the form when I click submit, and tells me if I have left the 'RefNo' field blank (in the final form there will be various fields to check, so I have used class='required' to identify them all). But so far, when I click submit, nothing happens (except the form is submitted with the missing data).
I've tried various options that I have found on the internet, and this seemed the most promising.
If anyone can see what I have done wrong it would be really appreciated.
<html>
<head>
<script language="JavaScript" src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function submitForm()
{
$("#Form1").submit(function()
{
$('.required input').each(function()
{
if ($(this).val() == '')
{
$(this).addClass('highlight');
}
}
);
if ($('.required input').hasClass('highlight'))
{
alert("Please fill in a Ref Number and try again");
return false;
}
}
);
}
</script>
</head>
<body>
<form method="POST" action="test9.php" name="Form1" ID="Form1">
<input TYPE="text" ID="RefNo" NAME="RefNo" VALUE="" size="25px" class="required"></input>
</br>
<p>
<input type="submit" Name="submit" id="submitButton" value="Report History" onClick='submitForm()'></input>
</p>
</form>
</body>
Your selectors should be $('input.required'), not $('.required input').
First, I think you should use Jquery validation plugin.
Ohterwise, this code should work :
-add a onsubmit="return submitForm()" in your Form tag
<form method="POST" action="test9.php" name="Form1" ID="Form1" onsubmit="return submitForm();">
-get rid of the onclick on the submit button
-and here is the submitForm function :
function submitForm() {
var valid = true;
$('input[class="required"]').each(function() {
if ($(this).val() === '') {
alert("One field is empty and try again");
valid = false;
}
});
return valid;
}
But I really recommend jquery.validate.js
Your selector appears to be a bit off:
It should be $('.required')
The way you have it tries to select an input nested inside a Required class.
Instead of doing it on form submit, remove the submit input type from the button and just have it be a regular button.
With that in mind, your javascript should be:
<script>
$('#submitButton').click(function () {
$('input.required').each(function() {
if ($(this).val() == '') {
$(this).addClass('highlight');
}
});
if ($('.highlight').length > 0) {
alert("Please fill in a Ref Number and try again");
return false;
}
else {
$('#Form1').submit();
}
});
</script>
Otherwise, the way that you're doing it, you would have to cancel the event until you run your check for missing data, and then submit the form anyway. This way keeps you from having to cancel the action, as older IE browsers do that differently than the other browsers, and even newer versions of IE. So it makes your code more readable.
The selector should be either $('input.required') or $('#RefNo').
$('#RefNo') is more faster since it uses native getElementById method.

How to grab the onSubmit event for a form?

I want to know how to grab the onsubmit event from a form to do some form validation, because I don't have access to it directly. (I am writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)
I got so frustrated trying to do this for my plugin that I have written a Hello World version below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop ups when the page loads.
Here is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Test</h2>
<form action="#" method="post" id="commentform">
<p><input type="text" name="author" id="author" size="22" tabindex="1" />
<label for="author"><small>Name (required)</small></label></p>
<p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />
</form>
<script type="text/JavaScript">
<!--
alert("Hello world");
var formCheck = document.getElementById("commentform");
formCheck.onSubmit = doMapping();
function doMapping() {
alert("form submitted");
return false;
}
-->
</script>
</body>
</html>
Change this:
formCheck.onSubmit = doMapping()
to this:
formCheck.onSubmit = doMapping
When you add parenthesis to the end of a function you execute that function. When you assign a function (or pass it as a parameter to another function) you need to omit the parenthesis as that is the way to retrieve a function pointer in JavaScript.
Edit: You will also need to move the declaration of the doMapping function above the assignment of that function to the onsubmit event like this (good catch tvanfosson!):
function doMapping() {
alert("form submitted");
return false;
}
formCheck.onSubmit = doMapping();
However if the doMapping function is not used elsewhere you can declare the doMapping function as an anonymous function like this:
formCheck.onSubmit = function() {
alert("form submitted");
return false;
}
which seems a bit cleaner to me.
Using jQuery.
$(document).ready( function() {
$('#commentform').submit( function() {
alert('form submitted');
return false;
});
});
Thank you! Actually I solved it another way, using both Andrew's suggestion and the window.onload event - I think the problem was partly because the element hadn't actually loaded.
window.onload = function(){
if (document.getElementById("commentform")){
document.getElementById("commentform").onsubmit = doMapping;
}
}
function doMapping(){
alert("form submitted");
return false;
}

Categories